100% found this document useful (1 vote)
75 views30 pages

C Sorting Searching Sample Source Codes: 2d Example Insertion Sort (Linked List)

The document contains code examples for various sorting algorithms implemented on different data structures, including arrays, linked lists, and strings. It includes implementations of insertion sort, binary search, bubble sort, selection sort, and heap sort. The examples sort integers, strings, and other data types using both recursive and iterative approaches. Overall the document serves as a reference for implementing classic sorting algorithms on standard data structures.

Uploaded by

Javed Khan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
100% found this document useful (1 vote)
75 views30 pages

C Sorting Searching Sample Source Codes: 2d Example Insertion Sort (Linked List)

The document contains code examples for various sorting algorithms implemented on different data structures, including arrays, linked lists, and strings. It includes implementations of insertion sort, binary search, bubble sort, selection sort, and heap sort. The examples sort integers, strings, and other data types using both recursive and iterative approaches. Overall the document serves as a reference for implementing classic sorting algorithms on standard data structures.

Uploaded by

Javed Khan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 30

C > Sorting Searching sample source

codes
2d example insertion sort [linked list]

#include <stdio.h>
#include <stdlib.h>

struct node {
int number;
struct node *next;
};

struct node *head = NULL;

/* insert a node directly at the right place in the linked list */


void insert_node(int value);

int main(void) {
struct node *current = NULL;
struct node *next = NULL;
int test[] = {8, 3, 2, 6, 1, 5, 4, 7, 9, 0};
int i = 0;

/* insert some numbers into the linked list */


for(i = 0; i < 10; i++)
insert_node(test[i]);

/* print the list */


printf(" before after\n"), i = 0;
while(head->next != NULL) {
printf("%4d\t%4d\n", test[i++], head->number);
head = head->next;
}

/* free the list */


for(current = head; current != NULL; current = next)
next = current->next, free(current);

return 0;
}

void insert_node(int value) {


struct node *temp = NULL;
struct node *one = NULL;
struct node *two = NULL;

if(head == NULL) {
head = (struct node *)malloc(sizeof(struct node *));
head->next = NULL;
}

one = head;
two = head->next;

temp = (struct node *)malloc(sizeof(struct node *));


temp->number = value;

while(two != NULL && temp->number < two->number) {


one = one->next;
two = two->next;
}

one->next = temp;
temp->next = two;
}

Binary search [int array]

#include <stdio.h>

#define TRUE 0
#define FALSE 1

int main(void) {
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int left = 0;
int right = 10;
int middle = 0;
int number = 0;
int bsearch = FALSE;
int i = 0;

printf("ARRAY: ");
for(i = 1; i <= 10; i++)
printf("[%d] ", i);

printf("\nSearch for Number: ");


scanf("%d", &number);
while(bsearch == FALSE && left <= right) {
middle = (left + right) / 2;

if(number == array[middle]) {
bsearch = TRUE;
printf("** Number Found **\n");
} else {
if(number < array[middle]) right = middle - 1;
if(number > array[middle]) left = middle + 1;
}
}

if(bsearch == FALSE)
printf("-- Number Not found --\n");

return 0;
}

Binary search [string pointer array]

#include <stdio.h>
#include <string.h>

static int binsearch(char *str[], int max, char *value);

int main(void) {
/* note, array needs to be sorted for bsearch... */
char *strings[] = { "bill", "chris", "jason", "randy", "trish" };
int i, asize, result;

i = asize = result = 0;

asize = sizeof(strings) / sizeof(strings[0]);

for(i = 0; i < asize; i++)


printf("%d: %s\n", i, strings[i]);

printf("\n");

if((result = binsearch(strings, asize, "randy")) != 0)


printf("`randy' found at position: %d\n", result);
else
printf("`randy' NOT found..\n");

if((result = binsearch(strings, asize, "nick")) != 0)


printf("`nick' found at %d\n", result);
else
printf("`nick' was NOT found..\n");

return 0;
}

static int binsearch(char *str[], int max, char *value) {


int position;
int begin = 0;
int end = max - 1;
int cond = 0;

while(begin <= end) {


position = (begin + end) / 2;
if((cond = strcmp(str[position], value)) == 0)
return position;
else if(cond < 0)
begin = position + 1;
else
end = position - 1;
}

return 0;
}

Bsort, bubble sort [array]

#include <stdio.h>

void bubble_sort(int a[], int size);

int main(void) {
int arr[10] = {10, 2, 4, 1, 6, 5, 8, 7, 3, 9};
int i = 0;

printf("before:\n");
for(i = 0; i < 10; i++) printf("%d ", arr[i]);
printf("\n");

bubble_sort(arr, 10);

printf("after:\n");
for(i = 0; i < 10; i++) printf("%d ", arr[i]);
printf("\n");

return 0;
}

void bubble_sort(int a[], int size) {


int switched = 1;
int hold = 0;
int i = 0;
int j = 0;

size -= 1;

for(i = 0; i < size && switched; i++) {


switched = 0;
for(j = 0; j < size - i; j++)
if(a[j] > a[j+1]) {
switched = 1;
hold = a[j];
a[j] = a[j + 1];
a[j + 1] = hold;
}
}
}

Bubble sort [linked list]

#include <stdio.h>
#include <stdlib.h>

#define MAX 10

struct lnode {
int data;
struct lnode *next;
} *head, *visit;

/* add a new entry to the linked list */


void llist_add(struct lnode **q, int num);
/* preform a bubble sort on the linked list */
void llist_bubble_sort(void);
/* print the entire linked list */
void llist_print(void);

int main(void) {
/* linked list */
struct lnode *newnode = NULL;
int i = 0; /* a general counter */
/* load some random values into the linked list */
for(i = 0; i < MAX; i++) {
llist_add(&newnode, (rand() % 100));
}

head = newnode;
printf("Before bubble sort:\n");
llist_print();
printf("After bubble sort:\n");
llist_bubble_sort();
llist_print();

return 0;
}

/* adds a node at the end of a linked list */


void llist_add(struct lnode **q, int num) {
struct lnode *tmp;

tmp = *q;

/* if the list is empty, create first node */


if(*q == NULL) {
*q = malloc(sizeof(struct lnode));
tmp = *q;
} else {
/* go to last node */
while(tmp->next != NULL)
tmp = tmp->next;

/* add node at the end */


tmp->next = malloc(sizeof(struct lnode));
tmp = tmp->next;
}

/* assign data to the last node */


tmp->data = num;
tmp->next = NULL;
}

/* print the entire linked list */


void llist_print(void) {
visit = head;

while(visit != NULL) {
printf("%d ", visit->data);
visit = visit->next;
}
printf("\n");
}

/* preform a bubble sort on the linked list */


void llist_bubble_sort(void) {
struct lnode *a = NULL;
struct lnode *b = NULL;
struct lnode *c = NULL;
struct lnode *e = NULL;
struct lnode *tmp = NULL;

/*
// the `c' node precedes the `a' and `e' node
// pointing up the node to which the comparisons
// are being made.
*/
while(e != head->next) {
c = a = head;
b = a->next;
while(a != e) {
if(a->data > b->data) {
if(a == head) {
tmp = b -> next;
b->next = a;
a->next = tmp;
head = b;
c = b;
} else {
tmp = b->next;
b->next = a;
a->next = tmp;
c->next = b;
c = b;
}
} else {
c = a;
a = a->next;
}
b = a->next;
if(b == e)
e = a;
}
}
}
Bubble sort [string array]

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 50
#define N 2000

void sort_words(char *x[], int y);


void swap(char **, char **);

int main(void) {
char word[MAX];
char *x[N];
int n = 0;
int i = 0;

for(i = 0; scanf("%s", word) == 1; ++i) {


if(i >= N)
printf("Limit reached: %d\n", N), exit(1);

x[i] = calloc(strlen(word)+1, sizeof(char));


strcpy(x[i], word);
}

n = i;
sort_words(x, n);
for(i = 0; i < n; ++i)
printf("%s\n", x[i]);

return(0);
}

void sort_words(char *x[], int y) {


int i = 0;
int j = 0;

for(i = 0; i < y; ++i)


for(j = i + 1; j < y; ++j)
if(strcmp(x[i], x[j]) > 0)
swap(&x[i], &x[j]);
}

void swap(char **p, char **q) {


char *tmp;

tmp = *p;
*p = *q;
*q = tmp;
}

Hsort, heap sort [array]

#include <stdio.h>
#include <stdlib.h>

/* array of MAXARRAY length ... */


#define MAXARRAY 5

/* preform the heapsort */


void heapsort(int ar[], int len);
/* help heapsort() to bubble down starting at pos[ition] */
void heapbubble(int pos, int ar[], int len);

int main(void) {
int array[MAXARRAY];
int i = 0;

/* load some random values into the array */


for(i = 0; i < MAXARRAY; i++)
array[i] = rand() % 100;

/* print the original array */


printf("Before heapsort: ");
for(i = 0; i < MAXARRAY; i++) {
printf(" %d ", array[i]);
}
printf("\n");

heapsort(array, MAXARRAY);

/* print the `heapsorted' array */


printf("After heapsort: ");
for(i = 0; i < MAXARRAY; i++) {
printf(" %d ", array[i]);
}
printf("\n");

return 0;
}
void heapbubble(int pos, int array[], int len) {
int z = 0;
int max = 0;
int tmp = 0;
int left = 0;
int right = 0;

z = pos;
for(;;) {
left = 2 * z + 1;
right = left + 1;

if(left >= len)


return;
else if(right >= len)
max = left;
else if(array[left] > array[right])
max = left;
else
max = right;

if(array[z] > array[max])


return;

tmp = array[z];
array[z] = array[max];
array[max] = tmp;
z = max;
}
}

void heapsort(int array[], int len) {


int i = 0;
int tmp = 0;

for(i = len / 2; i >= 0; --i)


heapbubble(i, array, len);

for(i = len - 1; i > 0; i--) {


tmp = array[0];
array[0] = array[i];
array[i] = tmp;
heapbubble(0, array, i);
}
}
Insertion sort [linked list]

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct lnode {
char *str;
struct lnode *next;
};

struct lnode *insert(char *data, struct lnode *list);


void free_list(struct lnode *list);
void print_list(struct lnode *list);

int main(void) {
char line[1024];
struct lnode *list;

list = NULL;
while((fgets(line, 1024, stdin)) != NULL)
list = insert(line, list);

print_list(list);
free_list(list);
return 0;
}

struct lnode *insert(char *data, struct lnode *list) {


struct lnode *p;
struct lnode *q;

/* create a new node */


p = (struct lnode *)malloc(sizeof(struct lnode));
/* save data into new node */
p->str = strdup(data);

/* first, we handle the case where `data' should be the first element */
if(list == NULL || strcmp(list->str, data) > 0) {
/* apperently this !IS! the first element */
/* now data should [be|becomes] the first element */
p->next = list;
return p;
} else {
/* search the linked list for the right location */
q = list;
while(q->next != NULL && strcmp(q->next->str, data) < 0) {
q = q->next;
}
p->next = q->next;
q->next = p;
return list;
}
}

void free_list(struct lnode *list) {


struct lnode *p;

while(list != NULL) {
p = list->next;
free(list);
list = p;
}
}

void print_list(struct lnode *list) {


struct lnode *p;

for(p = list; p != NULL; p = p->next)


printf("%s", p->str);
}

Isort, insertion sort [array]

#include <stdio.h>

void isort(float arr[], int n);


int fm(float arr[], int b, int n);

int main(void) {
float arr1[5] = {4.3, 6.7, 2.8, 8.9, 1.0};
float arr2[5] = {4.3, 6.7, 2.8, 8.9, 1.0};
int i = 0;

isort(arr2, 5);

printf("\nBefore\tAfter\n--------------\n");

for(i = 0; i < 5; i++)


printf("%.2f\t%.2f\n", arr1[i], arr2[i]);
return 0;
}

int fm(float arr[], int b, int n) {


int f = b;
int c;

for(c = b + 1; c < n; c++)


if(arr[c] < arr[f])
f = c;

return f;
}

void isort(float arr[], int n) {


int s, w;
float sm;

for(s = 0; s < n - 1; s++) {


w = fm(arr, s, n);
sm = arr[w];
arr[w] = arr[s];
arr[s] = sm;
}
}

Merge sort [linked list]

#include <stdio.h>
#include <stdlib.h>

struct node {
int number;
struct node *next;
};

/* add a node to the linked list */


struct node *addnode(int number, struct node *next);
/* preform merge sort on the linked list */
struct node *mergesort(struct node *head);
/* merge the lists.. */
struct node *merge(struct node *head_one, struct node *head_two);

int main(void) {
struct node *head;
struct node *current;
struct node *next;
int test[] = {8, 3, 2, 6, 1, 5, 4, 7, 9, 0};
int i;

head = NULL;
/* insert some numbers into the linked list */
for(i = 0; i < 10; i++)
head = addnode(test[i], head);

/* sort the list */


head = mergesort(head);

/* print the list */


printf(" before after\n"), i = 0;
for(current = head; current != NULL; current = current->next)
printf("%4d\t%4d\n", test[i++], current->number);

/* free the list */


for(current = head; current != NULL; current = next)
next = current->next, free(current);

/* done... */
return 0;
}

/* add a node to the linked list */


struct node *addnode(int number, struct node *next) {
struct node *tnode;

tnode = (struct node*)malloc(sizeof(*tnode));

if(tnode != NULL) {
tnode->number = number;
tnode->next = next;
}

return tnode;
}

/* preform merge sort on the linked list */


struct node *mergesort(struct node *head) {
struct node *head_one;
struct node *head_two;

if((head == NULL) || (head->next == NULL))


return head;
head_one = head;
head_two = head->next;
while((head_two != NULL) && (head_two->next != NULL)) {
head = head->next;
head_two = head->next->next;
}
head_two = head->next;
head->next = NULL;

return merge(mergesort(head_one), mergesort(head_two));


}

/* merge the lists.. */


struct node *merge(struct node *head_one, struct node *head_two) {
struct node *head_three;

if(head_one == NULL)
return head_two;

if(head_two == NULL)
return head_one;

if(head_one->number < head_two->number) {


head_three = head_one;
head_three->next = merge(head_one->next, head_two);
} else {
head_three = head_two;
head_three->next = merge(head_one, head_two->next);
}

return head_three;
}

Msort, merge sort [array]

#include <stdio.h>
#include <stdlib.h>

#define MAXARRAY 10

void mergesort(int a[], int low, int high);

int main(void) {
int array[MAXARRAY];
int i = 0;
/* load some random values into the array */
for(i = 0; i < MAXARRAY; i++)
array[i] = rand() % 100;

/* array before mergesort */


printf("Before :");
for(i = 0; i < MAXARRAY; i++)
printf(" %d", array[i]);

printf("\n");

mergesort(array, 0, MAXARRAY - 1);

/* array after mergesort */


printf("Mergesort :");
for(i = 0; i < MAXARRAY; i++)
printf(" %d", array[i]);

printf("\n");
return 0;
}

void mergesort(int a[], int low, int high) {


int i = 0;
int length = high - low + 1;
int pivot = 0;
int merge1 = 0;
int merge2 = 0;
int working[length];

if(low == high)
return;

pivot = (low + high) / 2;

mergesort(a, low, pivot);


mergesort(a, pivot + 1, high);

for(i = 0; i < length; i++)


working[i] = a[low + i];

merge1 = 0;
merge2 = pivot - low + 1;

for(i = 0; i < length; i++) {


if(merge2 <= high - low)
if(merge1 <= pivot - low)
if(working[merge1] > working[merge2])
a[i + low] = working[merge2++];
else
a[i + low] = working[merge1++];
else
a[i + low] = working[merge2++];
else
a[i + low] = working[merge1++];
}
}

No sort, but reversing a [linked list]

#include <stdio.h>
#include <stdlib.h>

#define MAX 10 /* max of 10 elements */

struct lnode {
int number;
struct lnode *next;
};

/* add a lnode at the beginning of the list */


void llist_add_begin(struct lnode **n, int val);
/* reverse the whole list */
void llist_reverse(struct lnode **n);
/* display the whole linked list */
void llist_display(struct lnode *n);

int main(void) {
struct lnode *new = NULL;
int i = 0;

/* insert some numbers */


for(i = 0; i <= MAX; i++)
llist_add_begin(&new, i);

printf("linked list before reversal:");


llist_display(new);
llist_reverse(&new);
printf("linked list after reversal:");
llist_display(new);
return 0;
}

/* add a lnode at the beginning of the list */


void llist_add_begin(struct lnode **n, int val) {
struct lnode *temp = NULL;

/* add new node */


temp = malloc(sizeof(struct lnode));
temp->number = val;
temp->next = *n;
*n = temp;
}

/* reverse the whole list */


void llist_reverse(struct lnode **n) {
struct lnode *a = NULL;
struct lnode *b = NULL;
struct lnode *c = NULL;
a = *n, b = NULL;

while(a != NULL) {
c = b, b = a, a = a->next;
b->next = c;
}

*n = b;
}

/* display the whole linked list */


void llist_display(struct lnode *n) {
while(n != NULL)
printf(" %d", n->number), n = n->next;

printf("\n");
}

Qcksort, quick sort [array]

#include <stdio.h>

#define MAXARRAY 10

void quicksort(int arr[], int low, int high);

int main(void) {
int array[MAXARRAY] = {0};
int i = 0;

/* load some random values into the array */


for(i = 0; i < MAXARRAY; i++)
array[i] = rand() % 100;

/* print the original array */


printf("Before quicksort: ");
for(i = 0; i < MAXARRAY; i++) {
printf(" %d ", array[i]);
}
printf("\n");

quicksort(array, 0, (MAXARRAY - 1));

/* print the `quicksorted' array */


printf("After quicksort: ");
for(i = 0; i < MAXARRAY; i++) {
printf(" %d ", array[i]);
}
printf("\n");

return 0;
}

/* sort everything inbetween `low' <-> `high' */


void quicksort(int arr[], int low, int high) {
int i = low;
int j = high;
int y = 0;
/* compare value */
int z = arr[(low + high) / 2];

/* partition */
do {
/* find member above ... */
while(arr[i] < z) i++;

/* find element below ... */


while(arr[j] > z) j--;

if(i <= j) {
/* swap two elements */
y = arr[i];
arr[i] = arr[j];
arr[j] = y;
i++;
j--;
}
} while(i <= j);

/* recurse */
if(low < j)
quicksort(arr, low, j);

if(i < high)


quicksort(arr, i, high);
}

Qsort [array of pointers to structures]

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node {
char *str;
};

/* compare function for qsort */


static int cmpr(const void *a, const void *b);

int main(void) {
struct node **strarray = NULL;
int i = 0, count = 0;
char line[1024];

while(fgets(line, 1024, stdin) != NULL) {


/* add ONE element to the array */
strarray = (struct node **)realloc(strarray, (count + 1) * sizeof(struct node *));

/* allocate memory for ONE `struct node` */


strarray[count] = (struct node *)malloc(sizeof(struct node));

/* copy the data into the new element (structure) */


strarray[count]->str = strdup(line);
count++;
}

/* before sorting ... */


printf("Before:\n");
for(i = 0; i < count; i++) {
printf("[%d]->str: %s", i, strarray[i]->str);
}

/* qsort array of structures */


qsort(strarray, count, sizeof(*strarray), cmpr);

/* after sorting ... */


printf("\n--\nAfter:\n");
for(i = 0; i < count; i++) {
printf("[%d]->str: %s", i, strarray[i]->str);
}

/* free all strarray elements */


for(i = 0; i < count; i++) {
free(strarray[i]->str);
free(strarray[i]);
i++;
}
free(strarray);

return 0;
}

/* compare function for qsort */


static int cmpr(const void *a, const void *b) {
struct node * const *one = a;
struct node * const *two = b;

return strcmp((*one)->str, (*two)->str);


}

Qsort [string array]

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void sortstrarr(void *array, unsigned n);


static int cmpr(const void *a, const void *b);

int main(void) {
char line[1024];
char *line_array[1024];
int i = 0;
int j = 0;
while((fgets(line, 1024, stdin)) != NULL)
if(i < 1024)
line_array[i++] = strdup(line);
else
break;

sortstrarr(line_array, i);

while(j < i)
printf("%s", line_array[j++]);

return 0;
}

static int cmpr(const void *a, const void *b) {


return strcmp(*(char **)a, *(char **)b);
}

void sortstrarr(void *array, unsigned n) {


qsort(array, n, sizeof(char *), cmpr);
}

Qsort [string, dynamic pointer array]

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void sortstrarr(void *array, unsigned n);


static int cmpr(const void *a, const void *b);

int main (void) {


char **strarray = NULL;
int i = 0, strcount = 0;
char line[1024];

while((fgets(line, 1024, stdin)) != NULL) {


if(strlen(line) == 1)
continue;

strarray = (char **)realloc(strarray, (strcount + 1) * sizeof(char *));


strarray[strcount++] = strdup(line);
}
printf("### Before ###\n");
for(i = 0; i < strcount; i++)
printf("%2d: %s", i, strarray[i]);

sortstrarr(strarray, strcount);

printf("### After ###\n");


for(i = 0; i < strcount; i++)
printf("%2d: %s", i, strarray[i]);

/* free mem... */
for(i = 0; i < strcount; i++)
free(strarray[i]);

free(strarray);
return 0;
}

static int cmpr(const void *a, const void *b) {


return strcmp(*(char **)a, *(char **)b);
}

void sortstrarr(void *array, unsigned n) {


qsort(array, n, sizeof(char *), cmpr);
}

Selection sort [linked list]

#include <stdio.h>
#include <stdlib.h>

#define MAX 10

struct lnode {
int data;
struct lnode *next;
} *head, *visit;

/* add a new entry to the linked list */


void llist_add(struct lnode **q, int num);
/* preform a selection sort on the linked list */
void llist_selection_sort(void);
/* print the entire linked list */
void llist_print(void);
int main(void) {
/* linked list */
struct lnode *newnode = NULL;
int i = 0; /* a general counter */

/* load some random values into the linked list */


for(i = 0; i < MAX; i++) {
llist_add(&newnode, (rand() % 100));
}

head = newnode;
printf("Before selection sort:\n");
llist_print();
printf("After selection sort:\n");
llist_selection_sort();
llist_print();

return 0;
}

/* adds a node at the end of a linked list */


void llist_add(struct lnode **q, int num) {
struct lnode *temp;

temp = *q;

/* if the list is empty, create first node */


if(*q == NULL) {
*q = malloc(sizeof(struct lnode));
temp = *q;
} else {
/* go to last node */
while(temp->next != NULL)
temp = temp->next;

/* add node at the end */


temp->next = malloc(sizeof(struct lnode));
temp = temp->next;
}

/* assign data to the last node */


temp->data = num;
temp->next = NULL;
}

/* print the entire linked list */


void llist_print(void) {
visit = head;

/* traverse the entire linked list */


while(visit != NULL) {
printf("%d ", visit->data);
visit = visit->next;
}
printf("\n");
}

void llist_selection_sort(void) {
struct lnode *a = NULL;
struct lnode *b = NULL;
struct lnode *c = NULL;
struct lnode *d = NULL;
struct lnode *tmp = NULL;

a = c = head;
while(a->next != NULL) {
d = b = a->next;
while(b != NULL) {
if(a->data > b->data) {
/* neighboring linked list node */
if(a->next == b) {
if(a == head) {
a->next = b->next;
b->next = a;
tmp = a;
a = b;
b = tmp;
head = a;
c = a;
d = b;
b = b->next;
} else {
a->next = b->next;
b->next = a;
c->next = b;
tmp = a;
a = b;
b = tmp;
d = b;
b = b->next;
}
} else {
if(a == head) {
tmp = b->next;
b->next = a->next;
a->next = tmp;
d->next = a;
tmp = a;
a = b;
b = tmp;
d = b;
b = b->next;
head = a;
} else {
tmp = b->next;
b->next = a->next;
a->next = tmp;
c->next = b;
d->next = a;
tmp = a;
a = b;
b = tmp;
d = b;
b = b->next;
}
}
} else {
d = b;
b = b->next;
}
}
c = a;
a = a->next;
}
}

Shsort, shell sort [array]

#include <stdio.h>

#define MAXARRAY 10

void shellsort(int a[], int total, int index);

int main(void) {
int array[MAXARRAY] = {0};
int i = 0;
/* load some random values into the array */
for(i = 0; i < MAXARRAY; i++)
array[i] = rand() % 100;

/* print the original array */


printf("Before shellsort: ");
for(i = 0; i < MAXARRAY; i++) {
printf(" %d ", array[i]);
}
printf("\n");

shellsort(array, MAXARRAY, 1);

/* print the `shellsorted' array */


printf("After shellsort: ");
for(i = 0; i < MAXARRAY; i++) {
printf(" %d ", array[i]);
}
printf("\n");

return 0;
}

void shellsort(int a[], int total, int index) {


int i = 0;
int j = 0;
int k = 0;
int l = 0;

for(k = 0; k < index; k++) {


for(i = k; i < total; i += index) {
l = a[i];
for(j = (i - index); j >= 0; j -= index) {
if(a[j] > l)
a[j + index] = a[j];
else
break;
}
a[j + index] = l;
}
}

return;
}
Ssort, selection sort [array]

#include <stdio.h>

void selection_sort(int a[], int size);

int main(void) {
int arr[10] = {10, 2, 4, 1, 6, 5, 8, 7, 3, 9};
int i = 0;

printf("before:\n");
for(i = 0; i < 10; i++) printf("%d ", arr[i]);
printf("\n");

selection_sort(arr, 10);

printf("after:\n");
for(i = 0; i < 10; i++) printf("%d ", arr[i]);
printf("\n");

return 0;
}

void selection_sort(int a[], int size) {


int i = 0;
int j = 0;
int large = 0;
int index = 0;

for(i = size - 1; i > 0; i--) {


large = a[0];
index = 0;
for(j = 1; j <= i; j++)
if(a[j] > large) {
large = a[j];
index = j;
}
a[index] = a[i];
a[i] = large;
}
}
Treesort [string array]

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct tnode {
char *str;
struct tnode *left;
struct tnode *right;
};

void insert(struct tnode **p, char *value);


void print(struct tnode *root);

int main(void) {
char line[1024];
struct tnode *root;

root = NULL;
while((fgets(line, 1024, stdin)) != NULL)
insert(&root, line);

print(root);
return 0;
}

/* call by reference .. ! */
void insert(struct tnode **p, char *value) {
if(!*p) {
*p = (struct tnode *)malloc(sizeof(struct tnode));
(*p)->left = (*p)->right = NULL;
(*p)->str = strdup(value);
return;
}

if(strcmp(value, (*p)->str) < 0)


insert(&(*p)->left, value);
else
insert(&(*p)->right, value);
}

/* inorder binary tree print ... */


void print(struct tnode *root) {
if(root != NULL) {
print(root->left);
printf("%s", root->str);
print(root->right);
}
}

C > Small Programs sample source codes

You might also like