What's wrong with this quicksort? [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
QuickSort. Code is written in pure C. Whats wrong with this algo implementation?
void quick_sort(void *base, size_t num, size_t size, int (*comp)(const void*, const void*)) {
unsigned int i = 0, j = num-1;
int rpos = rand() % num;
do {
while(comp((char*)base + size*i, (char*)base + rpos*size) < 0) i++;
while(comp((char*)base + size*j, (char*)base + rpos*size) > 0) j--;
if (i <= j) swap((char*)base + size*i++, (char*)base + size*j--, size);
} while (i <= j);
if (i < num) quick_sort((char*)base, j, size, comp);
if (j > 0) quick_sort((char*)base + size*i, num - i, size, comp);
}
It falls into infinite recursion.

There should be if(i<=j) swap and do . . . while(i<=j) not just (i < j ). And you need to increase i and decrease j after swap too.
There http://www.algolist.net/Algorithms/Sorting/Quicksort has sample code really easy to understand :)

If nothing else, it looks like you've got some off-by-one errors.
If num is supposed to be the number of elements to sort, then the array indices should go from 0 to num-1. By starting with j = num and comparing the value at base + size*j, you're consistently stepping outside your array bounds.
Also, try swapping your pivot element to either the beginning or end of your sorting region before doing the sweep; this will keep it from being stepped on...

Related

Finding the index of largest number [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 3 years ago.
Improve this question
I want to find the index of largest element in a given array in C .
I have tried insertion sort algorithm to determine the largest number in array after that I compared largest value with my all previous array's element and It did not work.
void insertion_array(float array[], int n) //* insertion algorithm*//
{
int i = 1, j;
float x;
for (; i < n; i++) {
x = array[i];
j = i - 1;
while ((j >= 0) && (array[j] > x)) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = x;
}
}
uint8_t Largest_Number_Finder(float arr[], uint8_t n) {
uint8_t index;
insertion_array(arr, n);
for (int i = 0; i < n; i++) {
if (arr[i] > arr[n - 1]) {
index = i;
}
}
return index;
}
I expected to take largest number index but Algorithm gives always last elements index. What should I do to make it right?
Edit=What you navigated as duplicate was to find largest element. I am aiming to find the index of largest element in array.
As "Some programmer dude" mentioned in the comment, if your purpose is to just find the index of the largest value, you don't need to implement insertion or any other algorithm to sort the array.
You can probably make a function like this.
int find_max_value(float array[], int length)
{
// set the value of index 0 as the "current max value"
float max_value = array[0];
// the same goes for the index number
int max_index = 0;
// go through the array
for(int i = 1; i < length; i++)
{
// if the next index's value is greater than the "current max value"
// update the max_value and max_index
if(array[i] > max_value)
{
max_value = array[i];
max_index = i;
}
}
return max_index;
}
and try calling that find_max_value() function with whatever input values, like
int result = find_max_value(array1, 10); // just an example supposing that you have declared an array called "array1" and its length is 10
printf("%d", result); // see what the return value of the find_max_value() function would be

Sorting an array - C language [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 5 years ago.
Improve this question
I have tried to write a sorting function sort(int *buffer, int array[], int size) which works in a way similar to the insertion sort - it takes the first element from the array, sets it as the first element of the buffer and then checks whether or not the next value showing up in the array is greater than the last value stored in the buffer. If yes, it keeps swapping the two elements until everything is in its place. This is my minimal working example:
#include <stdio.h>
void sort(int *buffer, int array[], int size) {
for(int i = 0; i < size; i++) {
buffer[i] = array[i];
while(i >= 1 && buffer[i] < buffer[i-1]) {
int tmp = buffer[i-1];
buffer[i-1] = buffer[i];
buffer[i] = tmp;
printf("i = %d i: %d, i -1 : %d \n",i, buffer[i], buffer[i-1]);
i--;
}
}
}
int main(void) {
int array[3] = {4,3,2};
int buffer[3];
sort(buffer, array, 3);
for(int i = 0; i < 3; i++) {
printf("%d", buffer[i]);
}
}
However, the output of this program is 222
To be honest, I don't see how it's even possible that three identical elements got placed in the buffer.
What can have gone wrong?
You are using the same variable for the inner while cycle and for the outer for loop. Use a different variable and copy the value of i to it in each iteration of the for.

Need help on an algorithm (stack overflow) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
This is a problem a friend of mine gave me as a challenge. I've managed to come up with a recursive algorithm that works fine for small inputs, however I get segmentation faults for large values. I suppose that's because of a stack overflow. I use the C language for solving the problem.
You are given an array of n numbers. Find and print the maximum length of the subset such that for any two numbers form that subset, the sum of the numbers is not divisible by k.
Input contains on the first line 2 numbers n and k, on the next line there are n numbers a[i] such that:
1 <= n <= 10^5
0 <= a[i] <= 10^9
1 <= k <= 100
# Example input:
4 3
1 7 4 2
# Output:
3
Explanation: (1 7 4) 1 + 7 = 8; 1 + 4 = 5; 7 + 4 = 11; all of them non-divisible by 3.
My solution is based on the following idea: For all numbers in the array check the sum with the others if it is divisible by k. If we find a match then create 2 arrays, one excluding the first term of the sum and one excluding the second one, this way we exclude such pairs from our subsets. Then do the same thing we did to the first array to both of them. If we have checked all the elements from the the array then set the solution to the length of the array and continue applying the "solver" to only the arrays that have a length greater than the solution already found. This algorithm works well for n < 47 , more than that and it gives me a seg fault. I would like to see any solution that solves the problem.
#include <stdio.h>
int n, k;
int * deleteElement(int * a, int n, int j){
int *c = (int*) malloc((n-1) * sizeof(int));
int k = 0;
for(int i = 0; i < n; i++){
if(i == j) continue;
c[k] = a[i];
k++;
}
return c;
}
int sol = 0;
void solver(int *a, int n, int *sol){
int *b, *c;
if(n <= *sol) return;
for(int i = 0; i < n-1; i++){
for(int j = i + 1; j < n; j++){
if((a[i] + a[j]) % k == 0){
c = deleteElement(a, n, i);
b = deleteElement(a, n, j);
solver(c, n-1, sol);
solver(b, n-1, sol);
return;
}
}
}
*sol = n;
}
int main(){
scanf("%d", &n);
scanf("%d", &k);
int a[n];
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
solver(a, n, &sol);
printf("%d\n", sol);
return 0;
}
You could use iteration to get rid of one of your two recursive calls, but that wouldn't help with stack space, since they have the same depth -- one call is as bad as 2.
It's easy enough to write a completely iterative algorithm that actually tests all the valid sets, but that's still an exponential time algorithm. In any case that this would save you from a stack overflow, it would take way too long to run. Since that algorithm would also suck, I don't want to write it.
A reasonable linear-time way to solve this problem is:
Calculate a map MODCOUNTS where MODCOUNTS[m] = the number of elements x such that x%k == m
Since any valid subset can only have one element divisible by k, if MODCOUNTS[0] > 1, then set MODCOUNTS[0]=1
Similarly, if k is even, and MODCOUNTS[k/2] > 1, then set MODCOUNTS[k/2]=1
Now, add up all the values in MODCOUNTS, but leave out a value MODCOUNTS[i] if:
i > 0, i*2 < k, AND MODCOUNTS[i] < MODCOUNTS[k-i]; OR
i*2 > k AND MODCOUNTS[i] <= MODCOUNTS[k-i]
rule 4 reflects that fact that a valid subset cannot include any elements x and y such that (x+y)%k = 0, for the cases that we didn't take care of in rules 2 and 3. The biggest valid subset includes all the elements from in MODCOUNTS[i], or all the elements in MODCOUNTS[k-i], but not elements from both.
If you use sparse data structure like a hash table to implement MODCOUNTS, then the whole thing takes O(N) time.

Getting the error in while loop '>': No conversion from 'int' to 'int *' [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 6 years ago.
Improve this question
I am Using Microsoft Visual Studio to compile the code. I get this error in the while loop for the condition a[i] > k:
'>': No conversion from 'int' to 'int *'
Here is the code:
/* Sort the array using Recursive insertion sort */
#include <stdio.h>
#include <conio.h>
void RecursiveInsertionSort(int a[], int);
/* Recursively call the function to sort the array */
void RecursiveInsertionSort(int *a, int n)
{
int i,k;
if (n > 1)
RecursiveInsertionSort(a, n - 1);//Call recursively
else {
k = a[n];
i = n - 1;
while (i >= 0 & & a[i] > k){
a[i + 1] = a[i]; //replace the bigger
i = i - 1;
}
a[i + 1] = k; //Place the key in its proper position
}
}
/* Main function */
void main()
{
int a[] = { 5,4,3,2,1 }; // Array unsorted declared
RecursiveInsertionSort(a, 5);//call recursive function to sort the array in ascending order
}
Can anyone please help me understand the error?
You have a space inside what should be the logical operator &&:
while (i >= 0 & & a[i] > k){
This is equivalent to
while (i >= 0 & &a[i] > k) {
which is a bitwise AND-operation between i >= 0 and &a[i] > k (two boolean values).
The &a[i] > k compares the address of a[i] (which is an int *) with k (which is an int). Hence the error.

Prime number into an array 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 6 years ago.
Improve this question
I try to do a function in order to sort an array and display after that only the prime number. But all the elements of my array are random numbers, and the problem is that the function display only negative prime numbers and not positive like 7 and 3, what can I do in order to solve the problem
int prime_arr(int size, int *arr, int *sort_arr)
{
int i, j, k = 0, flag;
for (i = 0; i < size; i++)
{
flag = 0;
for (j = 2; j < arr[i]/2; j++)
{
if (arr[i] % j == 0){
flag = 1;
break;
}
}
if (flag == 0){
sort_arr[k++] = arr[i];
}
}
return j;
}
I see 3 problems with the code:
1. You should return k, not j. k is the size of sort_arr
2. You should loop until arr[i] / 2, not one less than that (see <= in code below)
3. You do not handle negative numbers. Change your loop to the following:
for (j = 2; j <= abs(arr[i])/2; j++)
Without the code that prints your values, I'm not sure exactly what you're looking for, but hopefully fixing these will fix your problem.

Resources