Assume the following list of keys: 28, 18, 21, 10, 25, 30, 12, 71, 32, 58, 15 This list is to be sorted using insertion sort as described in this chapter for array-based lists. Show the resulting list after six passes of the sorting phase—that is, after six iterations of the for loop.
#include <iostream>
using namespace std;
void insertion_sort(int* arr, int size)
{
int i, key, j;
for (i = 1; i < 6; i++)
{
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void print(int* arr, int size)
{
for(int i = 0; i!= size; ++i)
{
cout<<arr[i]<<'\t';
}
cout<<endl;
}
int main()
{
int arr[] = {28, 18, 21, 10, 25, 30, 12, 71, 32, 58, 15};
print(arr, 11);
insertion_sort(arr, 11);
print(arr, 11);
}
Comments
Leave a comment