/*! * file SelectionSortRecusion.cpp * author Hasan * date 20 June 2014 03:32:27 * Exercise:4.31 C++How to Program 4th Ed */ #include <iostream> #include <iomanip> #include <ctime> using namespace std; void selectionSort(int[], int); void printArray1(int[]); const int SIZE = 10; int MAXRANGE = 100; int main(){ int array[SIZE] = { 0 }; srand(time(0)); for (int i = 0; i < SIZE; i++){ array[i] = 1 + rand() % MAXRANGE; } cout << "Unsorted Array\n"; printArray1(array); cout << "Sorted Array\n"; selectionSort(array, SIZE); printArray1(array); cin.get(); return 0; } void selectionSort(int a[], int arraySize){ int temp; if (arraySize >= 1){ for (int i = 0; i < arraySize; i++){ if (a[i] < a[0]){ temp = a[i]; a[i] = a[0]; a[0] = temp; } } cout << "\n"<<a[0]<<"\n";//for debug purpose printArray1(a);//for debug purpose //Now array changes ..first element is i.e a[0] is &a[1] //so the for loop will compare this &a[1] which is first //element to the rest of the elements and a[0] will be the //smaller than all.then recursion will take &a[1] as first //element again and will continue.. selectionSort(&a[1],arraySize-1); } } void printArray1(int a[SIZE]){ for (int i = 0; i < SIZE; i++){ cout << setw(4) << a[i]<<" "; } cout << endl; }
output:
Unsorted Array 64 87 59 19 84 25 48 76 55 27 Sorted Array 19 19 87 64 59 84 25 48 76 55 27 25 25 87 64 84 59 48 76 55 27 -858993460 27 27 87 84 64 59 76 55 48 -858993460 -359215729 48 48 87 84 64 76 59 55 -858993460 -359215729 1703300 55 55 87 84 76 64 59 -858993460 -359215729 1703300 3578681 59 59 87 84 76 64 -858993460 -359215729 1703300 3578681 1 64 64 87 84 76 -858993460 -359215729 1703300 3578681 1 3970760 76 76 87 84 -858993460 -359215729 1703300 3578681 1 3970760 39668 08 84 84 87 -858993460 -359215729 1703300 3578681 1 3970760 3966808 -3 59215809 87 87 -858993460 -359215729 1703300 3578681 1 3970760 3966808 -3592158 09 0 19 25 27 48 55 59 64 76 84 87
Post a Comment