Selection sort in c++

C++ program for Selection sort. Here mentioned other language solution.

// Include header file
#include <iostream>
using namespace std;
/*
  C++ program for selection sort
*/
class MySort
{
	public:
    // Swap the array element
    void swap(int arr[], int x, int y)
    {
      // x and y are index of array
      int temp = arr[x];
      arr[x] = arr[y];
      arr[y] = temp;
    }
	void selectionSort(int arr[], int n)
	{
		int min = 0;
		// Execute loop from 0..n
		for (int i = 0; i < n; ++i)
		{
			// Get current index
			min = i;
			for (int j = i + 1; j < n; ++j)
			{
				if (arr[min] > arr[j])
				{
					// Get the minimum element index
					min = j;
				}
			}
			if (i != min)
			{
				// Swap minimum element at i index
				this->swap(arr, i, min);
			}
		}
	}
	// Display array elements
	void display(int arr[], int n)
	{
		for (int i = 0; i < n; ++i)
		{
			// Display element value
			cout << "  " << arr[i];
		}
		cout << "\n";
	}
};
int main()
{
	MySort *task = new MySort();
	// Array of integer elements
	int arr[] = {
		8 , 2 , 3 , 8 , 1 , 3 , 73 , 121 , 54 , 
      23 , 84 , 13 , 67 , 23 , 52
	};
	// Get the size of array
	int n = sizeof(arr) / sizeof(arr[0]);
	cout << " Before Sort :" << endl;
	task->display(arr, n);
	// Test
	task->selectionSort(arr, n);
	cout << " After Sort :" << endl;
	task->display(arr, n);
	return 0;
}

Output

 Before Sort :
  8  2  3  8  1  3  73  121  54  23  84  13  67  23  52
 After Sort :
  1  2  3  3  8  8  13  23  23  52  54  67  73  84  121


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved