By
admin on Sunday, May 23rd, 2010 |
391 Comments
Its a C program to be done in linux platform.
There are many ways to sort, including the qsort function provided by the C standard library. If you want to implement a sort algorithm yourself, selection sort is a good place to start. See below for my example of sorting an array of int :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const int N = 10;
const int MAX_VAL = 100;
void selectionSort(int *, int);
void printArray(const int *, int);
int random(int range);
int main(int argc, char *argv[]) {
time_t t;
int *intArray,i;
/* allocate int array */
intArray = (int *)malloc(N * sizeof(int));
/* fill array */
srand((unsigned)time(&t));
for (i = 0; i < N; i++) {
intArray[i] = random(MAX_VAL);
}
printf("unsorted : ");
printArray(intArray,N);
selectionSort(intArray,N);
printf(" sorted : ");
printArray(intArray,N);
free(intArray);
return 0;
}
void selectionSort(int *a, int n) {
int i, j, min, t;
for (i = 0; i < n; i++) {
min = i;
for (j = i+1; j < n; j++) {
if (a[j] < a[min]) {
min = j;
}
}
t = a[min];
a[min] = a[i];
a[i] = t;
}
}
void printArray(const int *a, int n) {
int i;
for (i = 0; i < n; i++) {
printf("%2d ",a[i]);
}
puts("");
}
int random(int range) {
float x = ((float)rand() / (float)RAND_MAX) * range;
return (int)x;
}
#if 0
Sample run:
unsorted : 18 11 87 62 91 74 30 67 38 1
sorted : 1 11 18 30 38 62 67 74 87 91
#endif