user2208569
user2208569

Reputation: 109

Broken selection sort C

I'm working on a selection sort.

My problem is that if you delete all of my code from "void sort", the program runs. As soon as you put all the code back in, "void sort" wont even get to the first "printf" function in "void sort". I don't know what is hanging everything up.

The second problem here is that this function should do this:

Run through they array[] with vars: x (starting point,) temp (temporary lowest number) and k (current number.) It should--for each iteration--start at x, set temp = x, set k = (x+1) and then k++ until it reaches the end of the array. If array[k] is less than array[temp] it should set temp equal to k. Then at the end: swap array[x] and array[temp] and start over at (x+1)

When it was working before, the only result I got was that x = 7 (the end of the list,) and it would only print the last number. :/ wat do

Also, not needed but a secondary question how the hell do I return the sorted array from a void function? Global vars? anything else?

#include <stdio.h>
#define SIZE 8

void sort(int array[], int size)
{
    printf("starting sort, declaring vars...");
    int temp, placeholder, x, k;
    printf("setting x...");
    x = 0;
    printf("size(%d), i(%d)", size, x);
    printf("starting sort loop...");
    while (x < (size - 1));
    {
        k = (x + 1);
        temp = x;
        while(k < size)
        {
            if(array[k] < array[temp])
                temp = k;
            k++;
        }
        printf("array[%d] is %d from array[%d]\n", x, array[temp], temp);
        placeholder = array[temp];
        array[temp]= array[x];
        array[x] = placeholder;
        printf("%d ", array[x]);
        x++;
    }
    printf("\n");
}

int main(void)
{
    int numbers[SIZE] = {4, 15, 16, 50, 8, 23, 42, 108 };
    int i;
    for (i = 0; i < SIZE; i++)
        printf("%d ", numbers[i]);
    printf("\ncounted and sorting...\n");
    sort(numbers, SIZE);
    for (int i = 0; i < SIZE; i++);
        printf("%d", numbers[i]);
    printf("\n");
    return 0;
}

Upvotes: 0

Views: 191

Answers (1)

raptortech97
raptortech97

Reputation: 507

I don't know if this was a mistake in writing the question or in your code, but

while (x < (size - 1));

is incorrect. It does nothing, and so will loop infinitely. Take out the semicolon to get the intended effect. Similarly,

for (int i = 0; i < SIZE; i++);

Should not have that semicolon. Also, you can't declare i there in proper C, and i is already declared, so it's better to just leave it at for (i = 0; ....

Upvotes: 2

Related Questions