+ 3

Is this insertion sort ?? Please check...

After watching animated presentation of insertion sort , I tried to implement it by myself....But I am not sure , whether I have implemented it correctly . So please guys check it and leave comments... #include <iostream> using namespace std ; int main() { int n ,r ,z , temp; cin >> n ; int arr[n]; for(r=0;r<n;r++) { cin >> arr[r] ; } for(r=1;r<n;r++) { for(z=r;z>0;z--) { if(arr[z-1] > arr[z]) { temp = arr[z-1] ; arr[z-1] = arr[z] ; arr[z] = temp ; } else { break ; } } } for(r=0;r<n;r++) { cout << arr[r] << endl ; } return 0; }

19th May 2017, 6:40 AM
Swapnil Thakur
Swapnil Thakur - avatar
8 Respostas
+ 5
Yours is bubble sort. Try this for insertion sort: void InsertionSort(int arr[],int n) { int key; for(int i=0;i<n;i++) { key=arr[i]; int j=i-1; while(j>=0&&arr[j]>key) { arr[j+1]=arr[j]; j--; } arr[j+1]=key; } }
19th May 2017, 9:52 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
@codE niNjA Both the codes will sort any input array in increasing order... Mine is a function which is to be added to a program and main is to be designed for use... Swapnil's Program is ready to sort any integer array which one will type in a console.
19th May 2017, 11:03 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
hi, il tested your program and it's OK what is the problem ?
19th May 2017, 8:13 AM
MBZH31
MBZH31 - avatar
+ 2
I want to know if it is bubble sort or insertion sort.....
19th May 2017, 9:41 AM
Swapnil Thakur
Swapnil Thakur - avatar
+ 2
Thanks a lot 😊😊 Kinshuk
19th May 2017, 11:42 AM
Swapnil Thakur
Swapnil Thakur - avatar
+ 2
Happy to help... 😊
19th May 2017, 11:44 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
Bubble sort. Least efficient method. Not good for large sorting.
20th May 2017, 7:31 AM
Paul Jensen
Paul Jensen - avatar