Hi,
I was trying to do insertion sort for the array data[5]={3,1,4,7,5}. But always '7' comes as the first element and the rest of it is sorted correctly. the program I had written was this:
int selsort(int data[], int n)
{
int temp,min_id=0,min=0,i;
for(i=0; i<=n-1; i++)
min=data[i];
{
for (int j=i+1; j<n; j++)
if(data[j]<min)
{
min=data[j];
min_id=j;
}
temp=data[i];
data[i]=data[min_id];
data[min_id]=temp;
}
//for printing the elements:
for (int k =0; k<=n-1; k++)
{
cout << data[k]<<endl;
}
cin.get();
return 0;
}
Selection for each n in array, iterate n-1
Insertion is much better for small arrays, and arrays that store mostly sorted data. http://www.algolist.net/Algorithms/
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void selectionSort(int arr[], int n) {
int i, j, minIndex, tmp;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
if (minIndex != i) {
tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
}
1 2 3 4 5 6 7 8 9 10 11 12
void insertionSort(int arr[], int length) {
int i, j, tmp;
for (i = 1; i < length; i++) {
j = i;
while (j > 0 && arr[j - 1] > arr[j]) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--;
}
}
}