Direct Insert Sort
Basic Ideas:
1. Starting from a[0], that is, starting from 1 elements is ordered, a[1]~a[n-1] is unordered.
2. Proceed from a[1] into the previously ordered array until n-1.
#include <stdio.h>
#define N 5
void insertsort (int a[], int n);
void swap (int *x, int *y);
void Insertsort (int a[], int n) {
int i,j;
For (I=1 i<n; i++) {
for (j=i; j>0 && a[j]<a[j-1]; j--) {
swap (&A[J), &a[j-1]);
}
}
void swap (int *x, int *y) {
int i = *x;
*x = *y;
*y = i;
}
int main (void) {
int a[n] = {2, 5, 3, 1, 8};
Insertsort (A, N);
int i;
For (i=0 i<n; i++)
printf ("%d", A[i]);
return 0;
}
Direct Selection Sort
Basic ideas:
1. Starting from 1, find the lowest number of subscript by contrast. And then the value of the next object and 0 exchange.
2. Cycle to exchange the value to 1 2 3 ... n-1.
#include <stdio.h>
#define N 5
void selectsort (int a[], int n);
void swap (int *x, int *y);
void Selectsort (int a[], int n) {
int i,j;
For (i=0 i<n; i++) {
int min = i;
For (j=i+1 j<n; j + +) {
if (A[j] < a[min]) {
min = j;
}
}
Swap (&a[i], &a[min]);
}
void swap (int *x, int *y) {
int i = *x;
*x = *y;
*y = i;
}
int main (void) {
int a[n] = {2, 5, 3, 1, 8};
Selectsort (A, N);
int i;
For (i=0 i<n; i++)
printf ("%d", A[i]);
return 0;
}