Friday, 4 November 2016
Program 1 - Insertion Sort
| #include <stdio.h> | |
| #include <conio.h> | |
| void insertion_sort(int a[], int n){ | |
| int i, j, temp; | |
| for(i = 1; i < n; i++){ | |
| temp = a[i]; | |
| for(j = i-1; j >= 0 && temp < a[j]; j--){ | |
| a[j+1] = a[j]; | |
| } | |
| a[j+1] = temp; | |
| } | |
| } | |
| int main(){ | |
| int i; | |
| int a[] = {5,4,3,2,1, -1, -2, -3}; | |
| int n = sizeof(a)/ sizeof(a[0]); | |
| insertion_sort(a,n); | |
| printf("The sorted array is: \n"); | |
| for(i = 0; i < n; i++){ | |
| printf("%d ", a[i]); | |
| } | |
| return 0; | |
| } |
Program 2 - Shell Sort
| #include <stdio.h> | |
| #include <conio.h> | |
| void shell_sort(int a[], int n){ | |
| int gap, i, j, temp; | |
| for(gap = n/2; gap >= 1; gap /= 2){ | |
| for(i = gap; i < n; i++){ | |
| temp = a[i]; | |
| for(j = i-gap; j >= 0 && temp < a[j]; j -= gap){ | |
| a[j+gap] = a[j]; | |
| } | |
| a[j+gap] = temp; | |
| } | |
| } | |
| } | |
| int main(){ | |
| int i; | |
| int a[] = {10,9,8,7,6,9,5,-2,-3}; | |
| int n = sizeof(a)/ sizeof(a[0]); | |
| shell_sort(a,n); | |
| printf("The sorted array is: \n"); | |
| for(i = 0; i < n; i++){ | |
| printf("%d ", a[i]); | |
| } | |
| return 0; | |
| } | |
Subscribe to:
Posts (Atom)
