|
| 1 | +//sorting of linked list using insertion sort |
1 | 2 | #include <stdio.h>
|
2 |
| -#incude <stdlib.h> |
3 |
| -#define MAX 20 |
4 | 3 |
|
5 |
| -//i and j act as counters |
6 |
| -//arraySort is the array that is to be sorted |
7 |
| -//elmtToInsert will be the element that we will be trying to move to its correct index in the current iteration |
8 |
| - |
9 |
| -int main() |
10 |
| -{ |
11 |
| - int i, elmtToInsert , j , arraySort[MAX] = {0}; |
12 |
| - |
13 |
| - for(i = 1 ; i < MAX ; i++) //This array is being sorted in the ascending order. |
14 |
| - { |
15 |
| - elmtToInsert = arraySort[i]; //Pick up the ith indexed element of the array. It will be the elmtToInsert. |
16 |
| - j = i - 1 ; |
17 |
| - |
18 |
| - while(j >= 0 && elmtToInsert < arraySort[j]) /*compare it with each (i-1)th, (i-2)th... max 0th element, till the correct |
19 |
| - position of the elmtToInsert, where it is finally greater than the element just |
20 |
| - before it, is found */ |
21 |
| - { |
22 |
| - // You'll enter the loop if the elmtToInsert is less than the element just before it. |
23 |
| - |
24 |
| - arraySort[j+1] = arraySort[j]; //shift the current element one place forward to create room for insertion of the elmtToInsert |
25 |
| - j--; |
26 |
| - } |
27 |
| - //when we exit the loop, j+1 will be the index of the correct position of the elmtToInsert |
| 4 | +/*Displays the array, passed to this method*/ |
| 5 | +void display(int arr[], int n){ |
| 6 | + |
| 7 | + int i; |
| 8 | + for(i = 0; i < n; i++){ |
| 9 | + printf("%d ", arr[i]); |
| 10 | + } |
| 11 | + |
| 12 | + printf("\n"); |
| 13 | + |
| 14 | +} |
28 | 15 |
|
29 |
| - arraySort[j+1] = elmtToInsert ; //'insert' the elmtToInsert into its correct position |
30 |
| - |
| 16 | +/*This is where the sorting of the array takes place |
| 17 | + arr[] --- Array to be sorted |
| 18 | + size --- Array Size |
| 19 | + */ |
| 20 | +void insertionSort(int arr[], int size){ |
| 21 | + int j,temp,i; |
| 22 | + for(i=0; i<size; i++) { |
| 23 | + temp = arr[(j=i)]; |
| 24 | + while(--j >= 0 && temp < arr[j]) { |
| 25 | + arr[j+1] = arr[j]; |
| 26 | + arr[j] = temp; |
31 | 27 | }
|
32 |
| - |
| 28 | + } |
| 29 | +} |
33 | 30 |
|
34 |
| - return EXIT_SUCCESS; |
| 31 | +int main(int argc, const char * argv[]) { |
| 32 | + int n; |
| 33 | + printf("Enter size of array:\n"); |
| 34 | + scanf("%d", &n); // E.g. 8 |
| 35 | + |
| 36 | + printf("Enter the elements of the array\n"); |
| 37 | + int i; |
| 38 | + int arr[n]; |
| 39 | + for(i = 0; i < n; i++){ |
| 40 | + scanf("%d", &arr[i] ); |
| 41 | + } |
| 42 | + |
| 43 | + printf("Original array: "); |
| 44 | + display(arr, n); // Original array : 10 11 9 8 4 7 3 8 |
| 45 | + |
| 46 | + insertionSort(arr, n); |
| 47 | + |
| 48 | + printf("Sorted array: "); |
| 49 | + display(arr, n); // Sorted array : 3 4 7 8 8 9 10 11 |
| 50 | + |
| 51 | + return 0; |
35 | 52 | }
|
| 53 | + |
0 commit comments