Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //C program for insertion sort
- #include <math.h>
- #include <stdio.h>
- #include <conio.h>
- void insertionSortDes(int arr[], int n)
- {
- int i, key, j;
- for (i = 1; i < n; i++) {
- key = arr[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 && arr[j] < key) {
- arr[j + 1] = arr[j];
- j = j - 1;
- }
- arr[j + 1] = key;
- }
- }
- /* Function to sort an array using insertion sort*/
- void insertionSortAss(int arr[], int n)
- {
- int i, key, j;
- for (i = 1; i < n; i++) {
- key = arr[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 && arr[j] > key) {
- arr[j + 1] = arr[j];
- j = j - 1;
- }
- arr[j + 1] = key;
- }
- }
- // A utility function to print an array of size n
- void printArray(int arr[], int n)
- {
- int i;
- printf("\n");
- for (i = 0; i < n; i++)
- printf("%d ", arr[i]);
- printf("\n");
- }
- /* Driver program to test insertion sort */
- int main()
- {
- int i,arr[100],n;
- char ch;
- printf("enter the number of elements to be inserted : ");
- scanf("%d",&n);
- for(i=0;i<n;i++)
- {
- scanf("%d",&arr[i]);
- }
- printf("1> to sort in ascending order\n2>to sort in descending order");
- printf("\nenter your choice");
- fflush(stdin);
- ch=getche();
- switch(ch)
- {
- case '1':
- insertionSortAss(arr, n);
- printArray(arr, n);
- break;
- case '2':
- insertionSortDes(arr, n);
- printArray(arr, n);
- break;
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment