Is it okay for Insertion Sort? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
20th Jun 2020, 5:35 PM
Jubaer Ahmad
Jubaer Ahmad - avatar
9 Answers
+ 2
Jubaer Ahmad Yes, but its worst runtime is O(n²), whereas Heapsort and Mergesort have a worst runtime of only O(n lg n).
21st Jun 2020, 2:42 AM
SapphireBlue
SapphireBlue - avatar
+ 1
When ever you write the swap method you have to check for the pointer identity as below. Obviously this code works fine without that, but follow the practices. void swap(int *a, int *b) { int temp; if(a != b) { temp = *a ; *a = *b ; *b = temp ; } }
20th Jun 2020, 6:28 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 1
Jubaer Ahmad There is not a problem. If you pass array the second copy of array has to be made. This will add some latency in your code. Latency means code execution time.
20th Jun 2020, 6:33 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
20th Jun 2020, 6:40 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
0
Why are you passing array? Don't you think for pointer? you can use void InsertionSort(int *arr, const int& n) instead of void InsertionSort(int arr[], int n).
20th Jun 2020, 6:18 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
0
$¢𝐎₹𝔭!𝐨𝓝 So where's the problem by doing this?
20th Jun 2020, 6:26 PM
Jubaer Ahmad
Jubaer Ahmad - avatar
0
In next level you can templatize the code to work with other data types also.
20th Jun 2020, 6:30 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
0
$¢𝐎₹𝔭!𝐨𝓝 okay, but the best complexity of Insertion sort is O(n). My code has same complexity like this?
20th Jun 2020, 6:32 PM
Jubaer Ahmad
Jubaer Ahmad - avatar
0
Hello Jubaer Ahmad I made some changes on your code I think u will see this code https://code.sololearn.com/cOBneZeKT0A0/?ref=app
21st Jun 2020, 6:36 PM
Noman
Noman - avatar