-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSelectionSort.cpp
60 lines (48 loc) · 1.13 KB
/
SelectionSort.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
/*
link : https://practice.geeksforgeeks.org/problems/selection-sort/1#
Given an unsorted array of size N, use selection sort to sort arr[] in increasing order by repeatedly selecting the minimum element
from unsorted subarray and putting it in the sorted subarray.
Example 1:
Input:
N = 5
arr[] = {4, 1, 3, 9, 7}
Output:
1 3 4 7 9
*/
void selectionSort(int arr[], int n)
{
int min_index=0;
for(int i=0;i<n-1;i++)
{ min_index=i;
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[min_index])
{
min_index=j;
}
}
swap(&arr[i],&arr[min_index]);
}
}
//----------------------------------------------------------------- stable selection sort
void selectionSort(int arr[], int n)
{
int min_index=0;
for(int i=0;i<n-1;i++)
{ min_index=i;
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[min_index])
{
min_index=j;
}
}
int min = arr[min_index];
while(min_index>i)
{
arr[min_index] = arr[min_index-1];
min_index--;
}
arr[i]=min;
}
}