112 lines
1.9 KiB
C
112 lines
1.9 KiB
C
#include<stdio.h>
|
|
#include<stdlib.h>
|
|
#include<time.h>
|
|
|
|
struct block_ {
|
|
int value;
|
|
struct block_* next;
|
|
};
|
|
|
|
typedef struct block_ block;
|
|
typedef block* list;
|
|
|
|
void showList(list l) {
|
|
block* b = l;
|
|
while (b != NULL) {
|
|
printf("%d ", b->value);
|
|
b = b->next;
|
|
}
|
|
puts("");
|
|
}
|
|
|
|
list insert(list l, int value, int index) {
|
|
block* b = l;
|
|
if (index == -1) {
|
|
while (b->next != NULL) b = b->next;
|
|
block* new_block = malloc(sizeof(block));
|
|
new_block->value = value;
|
|
b->next = new_block;
|
|
return l;
|
|
} else if (index == 0) {
|
|
block* new_block = malloc(sizeof(block));
|
|
new_block->value = value;
|
|
new_block->next = l;
|
|
return new_block;
|
|
} else {
|
|
for (int i = 0; i < index-1; i++) {
|
|
b = b->next;
|
|
}
|
|
|
|
block* new_block = malloc(sizeof(block));
|
|
new_block->value = value;
|
|
new_block->next = b->next;
|
|
b->next = new_block;
|
|
return l;
|
|
}
|
|
}
|
|
|
|
list suppress(list l, int index) {
|
|
if (index == 0) return l->next;
|
|
else {
|
|
block* b = l;
|
|
for (int i = 0; i < index-1; i++) {
|
|
b = b->next;
|
|
}
|
|
|
|
if (b->next->next != NULL) b->next = b->next->next;
|
|
else b->next = NULL;
|
|
|
|
return l;
|
|
}
|
|
}
|
|
|
|
list sort(list l) {
|
|
list sorted = NULL;
|
|
while (l != NULL) {
|
|
int index = 0;
|
|
int max_index = 0;
|
|
block* max = malloc(sizeof(block));
|
|
max->value = 0;
|
|
block* curr = l;
|
|
|
|
while (curr != NULL) {
|
|
if (curr->value > max->value) {
|
|
max_index = index;
|
|
max = curr;
|
|
}
|
|
|
|
index++;
|
|
curr = curr->next;
|
|
}
|
|
|
|
l = suppress(l, max_index);
|
|
sorted = insert(sorted, max->value, 0);
|
|
}
|
|
|
|
return sorted;
|
|
}
|
|
|
|
list randList() {
|
|
list l = NULL;
|
|
srand(time(NULL));
|
|
for (int i = 0; i < 10; i++) {
|
|
srand(rand());
|
|
int random = rand() % (999-111) + 111;
|
|
block* new_m = malloc(sizeof(block));
|
|
new_m->value = random;
|
|
if (l != NULL) new_m->next = l;
|
|
l = new_m;
|
|
}
|
|
|
|
return l;
|
|
}
|
|
|
|
int main(int argc, char * argv[]) {
|
|
list l = randList();
|
|
showList(l);
|
|
l = sort(l);
|
|
showList(l);
|
|
return EXIT_SUCCESS;
|
|
}
|
|
|