In: Computer Science
Using C language:
void show_array (int data[ ], int n);
void InsertionSort (int data[ ], int n);
void SelectionSort (int data[ ], int n);
where data[] is the array and n is the size of the array.
If you implement both sort routines you will need to make a copy of the original unsorted array before using the first sort, or else the second sort will be working on a sorted version of the array.
#include<stdio.h>
//function to display the array content
void show_array (int data[], int n) {
printf("\n\nArray contents are: \n");
for(int i = 0 ; i < n ; i ++) {
printf("%d ", data[i]);
}
}
/* Function to sort an array using insertion sort*/
void InsertionSort(int data[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = data[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && data[j] > key)
{
data[j + 1] = data[j];
j = j - 1;
}
data[j + 1] = key;
}
}
void SelectionSort(int data[], int n)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (data[j] < data[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
int temp = data[min_idx];
data[min_idx] = data[i];
data[i] = temp;
}
}
int main() {
int n;
///reading user input
printf("Enter the size of array: ");
scanf("%d", &n);
//declaring array of size n
int data[n];
//reading array content from the user
printf("Enter array values: \n");
for(int i = 0 ; i < n ; i ++) {
scanf("%d", &data[i]);
}
//creating a copy of original array
int temp[n];
for(int i = 0 ; i < n ; i ++) {
temp[i] = data[i];
}
//insertoin sort on copy array
show_array(temp, n);
printf("\n\nInsertion Sort");
InsertionSort(temp, n);
show_array(temp, n);
//selection sort of original array
show_array(data, n);
printf("\n\nSelection Sort");
InsertionSort(data, n);
show_array(data, n);
}
IF THERE IS ANYTHING THAT YOU DO NOY UNDERSTAND, IR NEED MORE HELP THEN PLEASE MENTION IT IN THE COMMENTS SECTION.