Skip to content

Instantly share code, notes, and snippets.

@kdmkdmkdm
Created May 2, 2012 15:25
Show Gist options
  • Select an option

  • Save kdmkdmkdm/2577449 to your computer and use it in GitHub Desktop.

Select an option

Save kdmkdmkdm/2577449 to your computer and use it in GitHub Desktop.
selectionSortFinished
// giSelectionSort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int x[10];
cout << "Enter ten unsorted integers..." << endl;
for(int i = 0; i < 10; ++i)
{
cout << "[" << i << "] = ";
cin >> x[i];
}
cout << endl;
// list integers
cout << "Unsorted List = ";
for(int i = 0; i < 10; ++i)
{
cout << x[i] << ", ";
}
cout << endl;
cout << "Sorting..." << endl;
// sort integers
int temp = 0;
int min = 0;
for(int i = 0; i < 10; ++i)
{
// Set the current minimum index of the element used to test in
// the next for loop.
min = i;
for (int j = i + 1; j < 10; j++)
{
// If current element of this loop is less than the value at the index
// position of "min" then re-assign "min" to this new minimum
if (x[j] < x[min])
{
min = j;
}
}
// "min" is the index of the minimum element so swap it with
// the current position. Don't waste time swapping if the min index
// IS the current index
if (min != i)
{
int temp = x[min];
x[min] = x[i];
x[i] = temp;
}
}
// list sorted integers
cout << "Sorted List = ";
for(int i = 0; i < 10; ++i)
{
cout << x[i] << ", ";
}
cout << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment