forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
selection_sort.c
111 lines (85 loc) · 2.59 KB
/
selection_sort.c
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
selection sort is an in-place comparison sorting algorithm. It has an O(n²) time complexity,
which makes it inefficient on large lists, and generally performs worse than the similar insertion
sort.
Time complexity:O(n^2)
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the
unsorted subarray is picked and moved to the sorted subarray.
arr[] = 64 25 12 22 11 min(11,25,12,22,64)=11
// Find the minimum element in arr[0...4]
// and place it at beginning
11 25 12 22 64 min(12,25,22,64) = 12
// Find the minimum element in arr[1...4]
// and place it at beginning of arr[1...4]
11 12 25 22 64 min(25,22,64) = 22
// Find the minimum element in arr[2...4]
// and place it at beginning of arr[2...4]
11 12 22 25 64 min(25,64) = 25
// Find the minimum element in arr[3...4]
// and place it at beginning of arr[3...4]
11 12 22 25 64 min(64) = 64
*/
#include <stdio.h>
#include <stdlib.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
//create a array dynamically
int *create(int n)
{
int *a = (int *)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
{
/* take input using element */
scanf("%d", (a + i));
}
return a;
}
//display the arrray
void display(int *a, int n)
{
for (int i = 0; i < n; i++)
{
/* display it */
printf("%d", *(a + i));
printf(" ");
}
}
//selection sort function
int *selection_sort(int *a, int n)
{
int i, j, min_index;
// One by one move boundary of unsorted subarray
for (i = 0; i < n - 1; i++)
{
// Find the minimum element in unsorted array
min_index = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min_index])
min_index = j;
// Swap the found minimum element with the first element
swap(&a[min_index], &a[i]);
}
return a;
}
int main(int argc, char const *argv[])
{
int n;
printf("\nenter teh size of the array:");
scanf("%d", &n);
int *a = create(n);
printf("\nunsorted array:");
display(a, n);
int *b = selection_sort(a, n);
printf("\n\nsorted array:");
display(b, n);
return 0;
}