Skip to content

Instantly share code, notes, and snippets.

@nagolove
Created May 12, 2026 17:13
Show Gist options
  • Select an option

  • Save nagolove/0a35cafb01641c94fe49c3154fe899c3 to your computer and use it in GitHub Desktop.

Select an option

Save nagolove/0a35cafb01641c94fe49c3154fe899c3 to your computer and use it in GitHub Desktop.
//usr/bin/env gcc "$0" -o /tmp/_tmp_out && /tmp/_tmp_out; rm -f /tmp/_tmp_out; exit
#include <stdio.h>
#include <string.h>
enum { DATA_LEN = 100, INDEX_RANGE = 101 };
static void list_from_array(int *B, const int *A, size_t len) {
memset(B, 0, sizeof(int) * INDEX_RANGE);
B[0] = A[0];
for (size_t i = 0; i < len - 1; i++)
B[A[i]] = A[i + 1];
B[A[len - 1]] = 0;
}
static void list_print(const int *B) {
int v = B[0];
while (v) {
printf("%d ", v);
v = B[v];
}
printf("\n");
}
static void list_sort(int *B) {
int sorted = {0};
int curr = B[0];
B[0] = 0;
while (curr) {
int next = B[curr];
if (sorted == 0 || curr > sorted) {
B[curr] = sorted;
sorted = curr;
} else {
int v = sorted;
while (B[v] && B[v] > curr)
v = B[v];
B[curr] = B[v];
B[v] = curr;
}
curr = next;
}
B[0] = sorted;
}
int main(void) {
int A[DATA_LEN] = {0};
for (size_t i = 0; i < DATA_LEN; i++)
A[i] = i + 1;
int B[INDEX_RANGE] = {0};
list_from_array(B, A, DATA_LEN);
list_print(B);
list_sort(B);
list_print(B);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment