Day 21

Quick sort with linklist
:
#include <stdio.h>
#include <stdlib.h>


void quicksort(int *a, int p, int r);
int partition(int *a, int p, int r);


int main(void){


int* test;
int data,size,count=0;



//quicksort(test, 0, sizeof(test) / sizeof(int)-1);
//for (int i = 1; i<=size(test)+1; i++)
//printf("%d\n", test[0]);
//printf("Empty list\n");
int k=0;
printf("Enter max size of array \n");
scanf("%d", &size);
test=(int *)malloc(size*sizeof(int));
while (k != 2)
{


printf("Enter 1 to add list, 2 to quit. \n");
scanf("%d", &k);
if (k == 1)
{

printf("Enter data value to add: \n");
scanf_s("%d", &data);
test[count]=data;
quicksort(test,0,count);
count++;
printf("\nList\n");
for (int i = 0; i<count; i++)
printf("%d\n", test[i]);
//insert(test, data);

}

}
//system("pause");
return 0;
}


/* a[] is the array, p is starting index, that is 0,
and r is the last index of array. */

void quicksort(int *a, int p, int r)
{
if (p < r)
{
int q;
q = partition(a, p, r);
quicksort(a, p, q);
quicksort(a, q + 1, r);
}
}

int partition(int *a, int p, int r)
{
int i, j, pivot, temp;
pivot = a[p];
i = p;
j = r;
while (1)
{
while (a[i] < pivot && a[i] != pivot)
i++;
while (a[j] > pivot && a[j] != pivot)
j--;
if (i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else
{
return j;
}
}
}



Comments

Popular posts from this blog

Homework 6

Another Day 23

Homework4