forked from shivprime94/Data-Structure-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselectionSort.cpp
More file actions
51 lines (45 loc) · 924 Bytes
/
selectionSort.cpp
File metadata and controls
51 lines (45 loc) · 924 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
//C++ program for selection sort
//Time Complexity: O(n2)
//Space Complexity: O(1)
#include <bits/stdc++.h>
using namespace std;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void SelectionSort(int arr[], int n)
{
int i, j, min_indx;
for (i=0; i < n-1; i++)
{
min_indx = i;
for (j=i+1; j < n; j++)
if (arr[j] < arr[min_indx])
min_indx = j;
swap(&arr[min_indx], &arr[i]);
}
}
void PrintArray(int arr[], int n)
{
for (int i=0; i<n; i++)
cout<<arr[i]<< " ";
cout<<endl;
}
int main()
{
int n;
cout<<"Enter size of array: ";
cin>>n;
int arr[n];
cout<<"Enter array elements: \n";
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
SelectionSort(arr, n);
cout<<"Sorted array: \n";
PrintArray(arr, n);
return 0;
}