ccplusplus.com
Learn C, C++ Concepts
Thursday, February 16, 2012
selection sort example
/************************************************************************* * File : selection-sort.cpp * Author : Saurabh Gupta * Desc : selection sort example * Source : http://ccplusplus.com/p/c_15.html * Created : 10:20 AM Thursday, February 16, 2012 *************************************************************************/ #include
using namespace std; const int NUM_SIZE = 8; class CSelectionSort { private: int minIndex, tmp; int anUserNum [NUM_SIZE]; public: void m_selectionSort(int arr[], int n) { int i, j; for (i = 0; i < n - 1; i++) { minIndex = i; for (j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } if (minIndex != i) { tmp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = tmp; } } } void m_takeUserInput () { int nNum; cout << "Enter " << NUM_SIZE << "number to perform Selection Sort" << endl; for (int i = 0; i < NUM_SIZE; i++) { cin >> nNum; anUserNum [i] = nNum; } } void m_displayNumberAgaian () { for (int j = 0; j < NUM_SIZE; j++) { cout << anUserNum[j] << "\t"; } cout << "" << endl; } void m_performSort () { m_selectionSort (anUserNum, NUM_SIZE); } }; int main () { CSelectionSort ssort; ssort.m_takeUserInput (); cout << "performing Selection Sort on the following numbers : " << endl; ssort.m_displayNumberAgaian (); ssort.m_performSort (); cout << "Numbers after Selection Sort : " << endl; ssort.m_displayNumberAgaian (); return 0; } /* * * [sgupta@rhel6x86 data-structure]$ ./selection-sort Enter 8number to perform Selection Sort 5 1 12 -5 16 2 12 14 performing Selection Sort on the following numbers : 5 1 12 -5 16 2 12 14 Numbers after Selection Sort : -5 1 2 5 12 12 14 16 [sgupta@rhel6x86 data-structure]$ */
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment