From 4d62ca10d5f873aa1496f6a3cf57808826ca4680 Mon Sep 17 00:00:00 2001 From: jishnudas100 Date: Thu, 17 Oct 2019 19:45:06 +0530 Subject: [PATCH] added selection sort --- selectio-sort.cpp.txt | 68 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 selectio-sort.cpp.txt diff --git a/selectio-sort.cpp.txt b/selectio-sort.cpp.txt new file mode 100644 index 0000000..ce80317 --- /dev/null +++ b/selectio-sort.cpp.txt @@ -0,0 +1,68 @@ +#include +#include + +#define MAX 7 + +int intArray[MAX] = {4,6,3,2,1,9,7}; + +void printline(int count) { + int i; + + for(i = 0;i < count-1;i++) { + printf("="); + } + + printf("=\n"); +} + +void display() { + int i; + printf("["); + + // navigate through all items + for(i = 0;i < MAX;i++) { + printf("%d ", intArray[i]); + } + + printf("]\n"); +} + +void selectionSort() { + int indexMin,i,j; + + // loop through all numbers + for(i = 0; i < MAX-1; i++) { + + // set current element as minimum + indexMin = i; + + // check the element to be minimum + for(j = i+1;j < MAX;j++) { + if(intArray[j] < intArray[indexMin]) { + indexMin = j; + } + } + + if(indexMin != i) { + printf("Items swapped: [ %d, %d ]\n" , intArray[i], intArray[indexMin]); + + // swap the numbers + int temp = intArray[indexMin]; + intArray[indexMin] = intArray[i]; + intArray[i] = temp; + } + + printf("Iteration %d#:",(i+1)); + display(); + } +} + +void main() { + printf("Input Array: "); + display(); + printline(50); + selectionSort(); + printf("Output Array: "); + display(); + printline(50); +} \ No newline at end of file