-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselectionSort.cpp
More file actions
75 lines (51 loc) · 1.27 KB
/
selectionSort.cpp
File metadata and controls
75 lines (51 loc) · 1.27 KB
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
//
// selectionSort.cpp
// DataStructures
//
// Created by Suraj on 05/06/20.
// Copyright © 2020 Suraj. All rights reserved.
// select the starting position and find the minimum element and swap it with current one
// time O (n^2)
#include <iostream>
using namespace std;
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void selectionSort(int arr[], int size)
{
int i, j, min;
for(i = 0; i<size-1; i++)
{
min = i;
for(j = i+1; j<size; j++)
if (arr[j] < arr[min])
min = j;
swap(arr[i], arr[min]);
}
}
void display(int arr[], int size)
{
for(int i = 0; i<size; i++)
cout << arr[i] << " " ;
}
int main()
{
int size;
cout << "Enter the number of elements: ";
cin >> size;
int arr[size];
cout << "Enter elements:" << endl;
for(int i = 0; i<size; i++)
{
cin >> arr[i];
}
cout << "Array before Sorting: " << endl;
display(arr, size);
selectionSort(arr, size);
cout << "\n""Array after Sorting: " << endl;
display(arr, size);
}