summaryrefslogtreecommitdiffstats
path: root/C++/SortArrayExample2/SortArrayTemplate2.cpp
blob: 38ce9f9e550787dd94af76cdab733ed81bd79431 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Sort Array Example
// Ch 8
/*
   The selection sort algorithm rearranges a list by selecting an element in the list and moving it
   to its proper position. This algorithm finds the location of the smallest element in the unsorted
   portion of the list and moves it to the top of the unsorted portion of the list. The first time,
   we locate the smallest item in the entire list. The second time, we locate the smallest item in
   the list starting from the second element in the list, and so on.
   */

#include <iostream>

using namespace std;

// Constant declarations
const int ARRAY_SIZE = 8;

void sortArray(int list[]) {
	// Variable declarations
	int smallestIndex;
	int temp;
	// Outer FOR loop controls current location of the smallest index
	// notice that you iterate to one LESS than the array size

	for ( int i = 0; i < ARRAY_SIZE - 1; i++ ) {




		smallestIndex = i; // Find the location of the smallest element
		// sets smallest value to first item in array
		// Inner FOR loop iterates through the array to compare two values

		for (int currentLocation = i+1; currentLocation < ARRAY_SIZE; currentLocation++) {
			// ...if the current value is less than the current smallest value... 
			if (list[currentLocation] < list[smallestIndex]) {
				// ...then set the smallest value to the current value
				smallestIndex = currentLocation;
			}
		}

		// Move the smallest element to the beginning of the unsorted list - note 3 variables needed

		temp = list[smallestIndex];
		list[smallestIndex] = list[i];
		list[i] = temp;
	}	

	// Output sorted array

	cout << "Sorted Array: " << endl;
	for ( int i = 0; i < ARRAY_SIZE; i++) {
		cout << list[i] << endl;
	}
	cout << endl;

}

int main()
{
	//var dec
	int list[ARRAY_SIZE] = {16, 30, 24, 7, 62, 45, 5, 55};
	// Program title and description
	cout << "Selection Sort Example" << endl << endl;

	// Output original unsorted array
	for ( int i = 0; i < ARRAY_SIZE; i++) {
		cout << list[i] << endl;
	}
	cout << endl;

	sortArray(list);


	return 0;
}