sort.c

Commit: 5e92c85e Author: jokerz Raw Copy
1
/* sort.c — Sorting algorithms demo for Pactor64 */
2
#include "libc.h"
3
4
#define SIZE 10
5
6
static void fill_array(int arr[], int n) {
7
    /* Simple pseudo-random fill */
8
    unsigned long s = 42;
9
    for (int i = 0; i < n; i++) {
10
        s = s * 6364136223846793005ULL + 1442695040888963407ULL;
11
        arr[i] = (int)(s % 100);
12
    }
13
}
14
15
static void print_array(const char *label, int arr[], int n) {
16
    printf("  %s: [", label);
17
    for (int i = 0; i < n; i++) {
18
        printf("%d", arr[i]);
19
        if (i < n - 1) printf(", ");
20
    }
21
    printf("]\n");
22
}
23
24
static void bubble_sort(int arr[], int n) {
25
    for (int i = 0; i < n - 1; i++)
26
        for (int j = 0; j < n - i - 1; j++)
27
            if (arr[j] > arr[j + 1]) {
28
                int tmp = arr[j];
29
                arr[j] = arr[j + 1];
30
                arr[j + 1] = tmp;
31
            }
32
}
33
34
static void insertion_sort(int arr[], int n) {
35
    for (int i = 1; i < n; i++) {
36
        int key = arr[i], j = i - 1;
37
        while (j >= 0 && arr[j] > key) {
38
            arr[j + 1] = arr[j];
39
            j--;
40
        }
41
        arr[j + 1] = key;
42
    }
43
}
44
45
int main(int argc, char **argv) {
46
    printf("=== Sorting Algorithms Demo ===\n\n");
47
48
    int arr1[SIZE], arr2[SIZE];
49
    fill_array(arr1, SIZE);
50
51
    /* Copy for second sort */
52
    for (int i = 0; i < SIZE; i++) arr2[i] = arr1[i];
53
54
    print_array("Original", arr1, SIZE);
55
    printf("\n");
56
57
    bubble_sort(arr1, SIZE);
58
    print_array("Bubble sort   ", arr1, SIZE);
59
60
    insertion_sort(arr2, SIZE);
61
    print_array("Insertion sort", arr2, SIZE);
62
63
    /* Verify both sorted the same */
64
    int match = 1;
65
    for (int i = 0; i < SIZE; i++)
66
        if (arr1[i] != arr2[i]) match = 0;
67
68
    printf("\n  Results match: %s\n", match ? "YES" : "NO");
69
    printf("\nDone!\n");
70
    return 0;
71
}
72