QuickSort Algorithm in C [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm trying to write a recursive program for a QuickSort algorithm. Here's my code so far:
void QuickSort(int *array, int first, int last){
int q;
if (first<last){
q = partition(array,first,last);
QuickSort(array,first,q-1);
QuickSort(array,q+1,last);
}
}
void partition(int *A, int p, int r){
int value = A[r];
i = p-1;
int tmp;
for (j = p; j<=r; j++){
if (A[j] <= value) {
i++;
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
return(i);
}
int main(){
int numArray[8] = {30,15,11,40,75,80,70,60};
int i;
printf("Before sorting: \n");
for (i = 0; i<8; i++) printf("numArray[%d] = %d\n", i, numArray[i]);
int first = 0;
int last = sizeof(numArray)/sizeof(numArray[0]);
QuickSort(numArray,first,last-1);
printf("After sorting: \n");
for (i = 0; i<8; i++) printf("numArray[%d] = %d\n", i, numArray[i]);
}
My problem is that when I run this, I get stuck in an infinite loop when I get to the first recursion call (just after partition). Also, what I've noticed is that the recursion call is ran on the array values of A[0] - A[5], even though it should be on A[0]-A[3]. I'm not expecting a complete answer, but maybe a hint on why the program is stuck in that infinite would be extremely helpful.

Here's what I did with your outline and it seems to be working and sorting fine.
I replaced the void with an int, and declared int's as necessary
#include<iostream>
using namespace std;
int partition(int *A, int p, int r){
int value = A[r];
int i = p-1;
int tmp;
for (int j = p; j<=r; j++){
if (A[j] <= value) {
i++;
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
return(i);
}
void QuickSort(int *array, int first, int last){
int q;
if (first<last){
q = partition(array,first,last);
QuickSort(array,first,q-1);
QuickSort(array,q+1,last);
}
}
int main(){
int numArray[8] = {30,15,11,40,75,80,70,60};
printf("Before sorting: \n");
for (int i = 0; i<8; i++) printf("numArray[%d] = %d\n", i, numArray[i]);
int first = 0;
int last = sizeof(numArray)/sizeof(numArray[0]);
QuickSort(numArray,first,last-1);
printf("After sorting: \n");
for (int i = 0; i<8; i++) printf("numArray[%d] = %d\n", i, numArray[i]);
}

Related

Sorting program gives segmentation fault

I'm currently stuck on that little programm in C:
#include <stdio.h>
void print(int a[], int n) {
int index =0;
while (index <= n-1){
while (index != a[index]){
int temp;
temp = a[index];
a[index] = a[temp];
a[temp] = temp;
printf("%d\n", temp);
}
index = index+1;
}
int i;
for (i = 0; i<n; i++){
printf("%d\n", a[i]);
}
}
int main() {
int A[] = {0,6,5,1,3,20};
int n=6;
print(A,n);
return 0;
}
I have no idea why its not sorting and giving me that error...
Kind regard and thanks in advance

Segmentation fault on big array

I was using quicksort to see how fast it could order big arrays.
I ordered one million no problem.. 2 million no problem. 3 million gives a segfault. Some testing reveals it crashes somewhere between 2 million and 2.1 million, and GDB reveals the crash is from the "fill" function.
This is the code:
int partition(int v[], int N){
int i, j;
int x = v[N-1];
for(i = 0, j = 0; i < N - 1; i++){
if (v[i] < x) swap(v, j++, i);
}
swap(v, j, N - 1);
return j;
}
void quickSort(int v[], int N){
int p;
if (N > 1){
p = partition(v, N);
quickSort(v, p);
quickSort(v + p + 1, N - p - 1);
}
}
void fill(int v[], int N){
srand(clock());
for(int i = 0; i < N; i++){
v[i] = rand();
}
}
int main() {
int size = 3000000;
int v[size];
fill(v, size);
printf("ready\n\n");
quickSort(v, size);
for(int i = 0; i < size; i++)
printf("%d ", v[i]);
printf("\n\nDone\n\n");
return 0;
}
Is there any particular reason the code starts crashing at that particular number?
Thank you for any answers
With int size = 3000000;int v[size], you are creating a local variable on the "stack". The stack is - compared to the heap - rather limited; so 3000000 may exceed the available stack size, whereas 3000, for example, might not.
To create v on the heap, write
int *v = malloc(size);
and afterwards, check if you could allocate the desired space:
if (!v) {
printf("not enough space.");
return 1;
}
....

Radix Sorting Algorithm in c [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have been tried to write radix sort in c.when i run my code with the static array it works well. but when i am trying to take random inputs from file it gives me an "Segmentation fault" at run time.help Please just help to modify this code
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#include<string.h>
int getMax(int arr[], int n)
{
int mx = arr[0];
int i;
for (i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
void countSort(int arr[], int n, int exp,int base)
{
int output[n];
int i;
int count[base];
memset(count, 0, sizeof count);
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%base]++;
for (i = 1; i < base; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%base ] - 1] = arr[i];
count[ (arr[i]/exp)%base ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
void radixsort(int arr[], int n,int base)
{
int m = getMax(arr, n);
int exp;
for (exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp , base);
}
void print(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ",arr[i]);
}
int main(int argc,int argv[])
{
int base=atoi(argv[1]);
int num,i;
FILE *fp1=fopen("myFile1.txt","r");
int arr[50];
while(fscanf(fp1,"%d",&num)==1)
{
arr[i]=num;
i++;
}
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n ,base);
print(arr, n);
fclose(fp1);
return 0;
}
You are assuming that the compiler has set the initial value of i to 0. However, this is not guaranteed. While many compilers reset variables to 0, many others just leave the contents of memory set at whatever it happened to be at compile time or at load time. You need to initialize the value before using it.
Additionally, you do not test to ensure that you are not overrunning the arr buffer. For example consider what would happen to arr[] if you happen to open a file that has 51 entries. You would attempt to add an entry to arr[50] which overruns the buffer.
You need to initialize i to 0 and make sure to break out if i becomes too great.
The calculation of n is always 50 because arr is 50 ints. You should use i as the count of how many entries have been read in.
int main(int argc,int argv[])
{
int base=atoi(argv[1]);
// int num,i; // This is the line that causes the error
int num;
int i = 0; // This needs to be initialized before use.
FILE *fp1=fopen("myFile1.txt","r");
int arr[50];
// You need to ensure that i does not overrrun the buffer.
while(fscanf(fp1,"%d",&num)==1 && (i < 49))
{
arr[i]=num;
i++;
}
// Since i was defined before the while, it should have the correct count
// This calculation of n is wrong if fewer than a full buffer is read
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n, base);
print(arr, n);
fclose(fp1);
return 0;
}

Sorting output from high to low

I made a simple program that would just show the input as the output.
My main problem is that I want to sort the output from high to low.
Instead of being sorted from high to low, the output is just the same order as the input.
Can someone check my codes and see why it is not sorting.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#define size 7
#include<stdlib.h>
struct books
{
int profit;
};
void load(struct books b[], int n)
{
int i;
for (i = 0; i < n; i++)
{
printf("Enter profit:\n");
scanf("%d", &b[i].profit );
}
}
void print(struct books b[], int n)
{
int i;
for (i = 0; i<n; i++)
{
printf("Profit is:%d\n",b[i].profit);
}
}
void sort(struct books b[], int n)
{
int i; int j;
books t;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-1 ; j++)
if (b[j].profit < b[j + 1].profit)
{
t = b[j];
b[j] = b[j + 1];
b[j+1] = t;
}
}
void main()
{
books b[size];
load(b, size);
print(b, size);
sort(b, size);
system("pause");
}
If you want to print the sorted list, you need to call sort before calling print:
void main()
{
books b[size];
load(b, size);
sort(b, size);
print(b, size);
system("pause");
}
Also, I think you need to define the books struct as
struct books b[size];
if you want to avoid compiler errors.
Finally, to print the list from low to high rather than high to low you can either modify the sorting algorithm as suggested in the another answer, or you can modify the printing algorithm as below:
void print(struct books b[], int n)
{
int i;
for (i = n-1; i>0; i--)
{
printf("Profit is:%d\n",b[i].profit);
}
}
Use something like this(inverted bubble sort):
void inverted_sort(books b[], int size){
int profit;
bool swap;
do{
swap = false;
for (int i= 0; i < (size - 1); i++){
if (b[i].profit < b[i + 1].profit){
profit = b[i].profit;
b[i].profit = b[i + 1].profit;
b[i + 1].profit = profit;
swap = true;
}
}
} while (swap);
}
And remember to change the functions order, inverted_sort() must go before print().
void main()
{
books b[size];
load(b, size);
inverted_sort(b, size);
print(b, size);
}
Hope this helps!
use this :
void sort(struct books b[], int n)
{
int i; int j;
books t;
for (i = 0; i < n; i++)
for (j = i + 1; j < n ; j++)
if (b[j].profit > b[i].profit)
{
t = b[j];
b[j] = b[i];
b[i] = t;
}
}

Shell sorting random float array not working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I wrote a shell sorting algorithm which works perfectly on integer values, but gives me segmentation fault when trying to sort float numbers. Could you help me with this ? Thank you.
We have a homework at the university and my teacher wrote this program with insert sort and it worked. The homework for us was to rewrite it to shell sort (which I think I did correctly) and maybe expand it further more to sort strings and numbers from files.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <time.h>
int int_cmp(const void *p1, const void *p2){
return *(int*)p1 - *(int*)p2;
}
int float_cmp(const void *p1, const void *p2){
if (*(float*)p1 == *(float*)p2){
return 0;
}
else if (*(float*)p1 < *(float*)p2){
return -1;
}
else {
return 1;
}
}
void shell_sort(void *v, int nr, int size, int(*p_cmp)(const void*, const void*)){
int i, j;
void *pv, *pi, *pj;
pv = malloc(size); //this is where I get segmentation fault
for (int gap = nr/2; gap > 0; gap/=2){
for (i = gap; i < nr; ++i){
for (j = i-gap; j >= 0; j-=gap){
pi = v;
pi = (char*)pi+j*size;
pj = (char*)pi+gap*size;
if (p_cmp(pi, pj) > 0){
memcpy(pv, pi, size);
memcpy(pi, pj, size);
memcpy(pj, pv, size);
}
else {
break;
}
}
}
free(pv);
}
}
int main(){
int a[20], n = 20;
float b[25], m = 25;
srand(time(NULL));
printf("Original integer array: ");
for (int i = 0; i < 20; ++i){
a[i] = rand() % 100;
printf("%i ", a[i]);
}
printf("Original float array: ");
for (int j = 0; j < 25; ++j){
b[j] = (float)rand()/(float)(RAND_MAX)*50;
printf("%f ", b[j]);
}
shell_sort(a, n, sizeof(int), int_cmp);
shell_sort(b, m, sizeof(float), float_cmp);
printf("\nInteger array after sort: ");
for (int i = 0; i < 20; ++i){
printf("%i ", a[i]);
}
printf("\nFloat array after sort: ");
for (int j = 0; j < 25; ++j){
printf("%f ", b[j]);
}
return 0;
}
free(pv); move to outside for-loop(after loop).

Resources