-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSelection_sort.cpp
80 lines (61 loc) · 1.5 KB
/
Selection_sort.cpp
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
77
78
79
80
/*
Author: Parth Shah
Visualgo.net Data Structures Practice.
Bubble_Sort Implementation.
This sorting can be done on different data type such as Char, string, double.
Just change the type.
*/
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
//Prototype of the Function.
int display_array(int [], int);
int main()
{
//Creating an array with fixed size.
int numbers[10];
const int array_size = sizeof(numbers)/sizeof(numbers[0]);
//Filling the array with random numbers.
for(int m=0; m < array_size; m++)
{
int temp = rand() % 10 + 1;
numbers[m]= temp;
}
cout << "Numbers in unsorted form are as below." << endl;
display_array(numbers,array_size);
//Selection Sort Algorithm.
int smallest=0;
int smallest_index =0;
int temp_value = 0;
for(int i=0; i<array_size-1; i++)
{
smallest_index = i;
smallest = numbers[i];
for(int m=i+1; m < array_size; m++)
{
if( numbers[m] < smallest)
{
smallest=numbers[m];
smallest_index = m;
}
} //Swap two values.
temp_value = numbers[smallest_index];
numbers[smallest_index] = numbers[i];
numbers[i] = temp_value;
}
//Print out the soreted list.
cout << endl << "Sorted list is here! \n";
display_array(numbers,array_size);
cin.get();
return 0;
}
//Defining helper Functions.
int display_array(int temp_array[], int size)
{
//int temp_array_size = sizeof(temp_array)/sizeof(temp_array[0]);
for(int i =0; i< size; i++)
{
cout << temp_array[i] << " ";
}
}