-
Notifications
You must be signed in to change notification settings - Fork 74
/
Selectionsort.c
50 lines (39 loc) · 989 Bytes
/
Selectionsort.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
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, minIdx, temp;
for (i = 0; i < n - 1; i++) {
minIdx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int n;
// Prompt the user for the number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n]; // Declare an array of size n
// Read the elements from the user
printf("Enter %d numbers: \n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Original array: \n");
printArray(arr, n);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}