Remove negative numbers and sort an array

The while loop never stops, that’s probably the reason your code freezes.
Your code only changes the address when the if statement is true. Which the array in your main() will stuck on the second (a[1]) element. So if we change change the address when the if statement is false…

#include<stdio.h>
#include<stdlib.h>
void swap(int *p, int *q) {
    int h = *p;
    *p = *q;
    *q = h;
}

int remove_negatives(int *array, int length) {
    int *a, *head;
    int n = length;
    head = array;
    a = &array[n - 1];  
    for (int i = 0; i <= n - 1; i++) {
        while (array < a) {
            if (*array >= 0) {
                array++;
                continue;
            }
            swap(a, array);
            a--;
            array++;
            length--;
        }
    }
    for (int i=0; i<length; i++) {
        printf("%d ", *head);
        head++;
    }
    puts("");
    return length;
}

int main(void) {
    int a[] = {-1, 2, 4, -8, 3, 7, -8, 9, 3};
    int l = sizeof(a) / sizeof(a[0]);
    remove_negatives(a, l);
    return 0;
}

Now the while loop works, buts as @wovano said, the answer is still wrong. Your code isn’t exactly a “bubble sort”. you swap all the negative number to the end of the array and didn’t actually sort the array.

So, let’s start from the beginning.

To simplify the process, let bubble sort first, and then find the new array length.

#include<stdio.h>
#include<stdlib.h>
void swap(int *p, int *q) {
    int h = *p;
    *p = *q;
    *q = h;
}

int bubble_sort(int *array, int length) {
    int i, j;

    // Bubble sort
    for (i=0; i<length-1; i++) {
        for (j=i+1; j<length; j++) {
            if (array[i]<array[j]) swap(&array[i], &array[j]);
        }
    }

    // Find new array length
    for (i=length-1; i>=0; i--) {
        if (array[i]>=0) break;
        length--;
    }
    return length;
}

int main(void) {
    int a[] = {-1, 2, 4, -8, 3, 7, -8, 9, 3};
    int l = sizeof(a) / sizeof(a[0]);
    l = bubble_sort(a, l);
    for (int i=0; i<l; i++) printf("%d ", a[i]);
    puts("");

    return 0;
}

Leave a Comment