#include<stdio.h> /* * Implemented by Arjun Sunel. */ // Method to swap two integers by reference. void Swap(int *first, int *second) { int temp = *first; *first = *second; *second = temp; } // Insertion Sort Method void InsertionSort(int array[], int size) { int i, j, curElement; for(i = 1; i < size; i++) { curElement = array[i]; j = i - 1; while(j >=0 && array[j] > curElement) { Swap(&array[j+1], &array[j]); j--; } array[j+1] = curElement; } } // Entry point of the program int main() { int array[] = {5, -12, 14, 7}; int arraySize = 4; int index; printf("Before sorting : \n"); for(index = 0; index <= arraySize - 1; index++) { printf("%d ", array[index]); } InsertionSort(array, arraySize); printf("\nAfter sorting : \n"); for(index = 0; index <= arraySize - 1; index++) { printf("%d ", array[index]); } printf("\n"); }
Sunday, 14 December 2014
Iterative InsertionSort for Array of Integers
Labels:
Sorting
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment