forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection_sort.cpp
More file actions
56 lines (52 loc) · 979 Bytes
/
selection_sort.cpp
File metadata and controls
56 lines (52 loc) · 979 Bytes
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
//
// C++ implementation of selection sort
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/sorting
// https://github.com/allalgorithms/cpp
//
// Contributed by: Rituparno Biswas
// Github: @roopbiswas
//
#include <iostream>
// Swap elements
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
// Implement selection sort
void selectionSort(int arr[], int n)
{
int i, j, min_id;
for (i = 0; i < n-1; i++)
{
min_id=i;
for (j = i+1; j < n; j++)
if (arr[min_id] > arr[j])
min_id=j;
swap(&arr[i], &arr[min_id]);
}
}
// Function to print elements
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// test
int main()
{
int arr[] = {46, 24, 33, 10, 2, 81, 50};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Unsorted array: \n");
printArray(arr, n);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}