how to sort arrays in c language/*
Example: how to sort an int array in C language
*/
#include <stdio.h>
#include <stdlib.h>
void swap(int* xp, int* yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// selection sort function
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// iterate through array
for (i = 0; i < n - 1; i++) {
// Find the smallest element in an unsorted array
min_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Find the minimum value and exchange it with the first element
swap(&arr[min_idx], &arr[i]);
}
}
int main(int argc, char const *argv[])
{
int arr[] = {70,35,40,1,8,12,3,6,5};
int n = sizeof(arr)/sizeof(int);
printf("before sort\n");
for(int i=0 ; i< n ; i++)
{
printf("%d, ", arr[i]) ;
}
selectionSort(arr,n);
printf("\nafter sort\n");
for(int i=0 ; i< n ; i++)
{
printf("%d, ", arr[i]) ;
}
return 0;
}
ruoSce:www.lautturi.com