Selection Sort in C

Source Code

#include <stdio.h>
#include <malloc.h>

void main () {
	int i, j, k, n, *a, temp;
	
	printf("Please enter number of elements: ");
	scanf("%d", &n);
	a = (int *) malloc(n * sizeof(int));
	
	printf("Please enter array elements:\n");
	for(i=0; i<n; i++) {
		printf("Enter element no %d: ", i+1);
		scanf("%d", &a[i]);
	}
	
	for (i=0; i<n; i++) {
		j = i;
		for (k=i+1; k<n; k++) {
			if (a[k] < a[j]) j = k;
		}
		temp = a[i];
		a[i] = a[j];
		a[j] = temp;
		
		printf("\nPass %d:\t", i+1);
		for (k=0; k<n; k++) printf("%d ", a[k]);
		printf("\n");
	}
}

/* ==== selection sort ====
						i	j	k
-----------------------------------
	12 34 2 43 9 14		0	0	1
	2 34 12 43 9 14		1		
	2 9 12 43 34 14		2		
	2 9 12 43 34 14		3		
	2 9 12 14 34 43		4		
	2 9 12 14 34 43		5		
*/

Output

Please enter number of elements: 10
Please enter array elements:
Enter element no 1: 21   
Enter element no 2: 12
Enter element no 3: 54
Enter element no 4: 3
Enter element no 5: 78
Enter element no 6: 999
Enter element no 7: 2
Enter element no 8: 44
Enter element no 9: 75
Enter element no 10: 15

Pass 1:	2 12 54 3 78 999 21 44 75 15 

Pass 2:	2 3 54 12 78 999 21 44 75 15 

Pass 3:	2 3 12 54 78 999 21 44 75 15 

Pass 4:	2 3 12 15 78 999 21 44 75 54 

Pass 5:	2 3 12 15 21 999 78 44 75 54 

Pass 6:	2 3 12 15 21 44 78 999 75 54 

Pass 7:	2 3 12 15 21 44 54 999 75 78 

Pass 8:	2 3 12 15 21 44 54 75 999 78 

Pass 9:	2 3 12 15 21 44 54 75 78 999 

Pass 10:	2 3 12 15 21 44 54 75 78 999

Leave a Reply

Note: Your email address will not be published. Required fields are marked *