尝试进行气泡排序

时间:2018-10-27 14:26:43

标签: c

我认为这是C.,但试图弄清楚为什么我的气泡排序不起作用。我在跟踪一个现有示例,因此也许我与该代码的集成不正确,但不太确定。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) 
{
    if (argc != 2) {
        printf("%s <student-id>\n", argv[0]);
        exit(0);
    }

    int i;
    int size = 10000;
    int seed = atoi(argv[1]); 

    srand(seed % 4);

    int *int_array = malloc(sizeof(int)*size);
    for (i = 0; i < size; i++)
    {
        int_array[i] = rand();
    }

    // This part
    int j;
    for (i = 0; i < size; i += 1) {
        for (j = i - 1; j >= 0 && int_array[j] > int_array[j + 1]; j+= 1) {
            swap(int_array,j);
        }
    }


    int failed = 0;
    for (i = 0; i < size; i++)
    {
        if (int_array[i] < int_array[i+1])
        {
            failed = 1;
            break;
        }
    }

    free(int_array);

    return 0;
}

1 个答案:

答案 0 :(得分:0)

这是我的冒泡排序代码:

for (int i = 0; i < size; i += 1) 
{
    for (j = i + 1; j < size; j+= 1) 
    {
        //this for starts from i+1 because I want to compare element int_array[i] whith the rest of the array. Each time this for starts, int_array is sorted from 0 to i-1
        if(int_array[i] > int_array[j]) swap(int_array[i], int_array[j]);
    }
}