1 | #include<stdio.h> | |||
2 | void Selection_Sort(int a[],int n); | |||
3 | int main() | |||
4 | { | |||
5 | int a[10]; | |||
6 | int i,j,temp,n,key; | |||
7 | printf("Enter the no.of elements : "); | |||
8 | scanf("%d",&n); | |||
9 | for(i=0;i<n;i++) | |||
10 | { | |||
11 | printf("Enter a[%d] element : ",i); | |||
12 | scanf("%d",&a[i]); | |||
13 | } | |||
14 | printf("Before Sorting array elements are : "); | |||
15 | for(i=0;i<n;i++) | |||
16 | { | |||
17 | printf("%d ",a[i]); | |||
18 | } | |||
19 | Selection_Sort(a,n); | |||
20 | printf("\nafter Sorting array elements are : "); | |||
21 | for(i=0;i<n;i++) | |||
22 | { | |||
23 | printf("%d ",a[i]); | |||
24 | } | |||
25 | } | |||
26 | void Selection_Sort(int a[],int n) | |||
27 | { | |||
28 | int i,j,min,minat; | |||
29 | for(i=0;i<(n-1);i++) | |||
30 | { | |||
31 | minat=i; | |||
32 | min=a[i]; | |||
33 | for(j=i+1;j<n;j++) //select the min of the rest of array | |||
34 | { | |||
35 | if(min>a[j]) //ascending order for descending reverse | |||
36 | { | |||
37 | minat=j; //the position of the min element | |||
38 | min=a[j]; | |||
39 | } | |||
40 | } | |||
41 | int temp=a[i] ; | |||
42 | a[i]=a[minat]; //swap | |||
43 | a[minat]=temp; | |||
} | ||||
} | ||||
OUTPUT: Enter the no.of elements : 5 |
||||
Enter a[0] element : 8 | ||||
Enter a[1] element : 4 | ||||
Enter a[2] element : 6 | ||||
Enter a[3] element : 2 | ||||
Enter a[4] element : 3 | ||||
Before Sorting array elements are : 8 4 6 2 3 | ||||
after Sorting array elements are : 2 3 4 6 8 |
C Program for Selection Sort Arrange a list of Integers in Ascending order
Share to other apps