显示排序数组的输出会导致问题

Displaying the output of a sorted array causes problem

我尝试将冒泡排序算法应用于值数组。

我的输入中有 5000 个值,从 1 到 5000。我从文本文件导入值来创建数组,效果很好。冒泡排序算法也运行良好。

问题出在输出的某个地方。有些值根本不会出现在输出中,而有些值会被打印多次。我附上我的代码和输出图像以供参考。

#include<stdio.h>
#include<conio.h>
int main() {
    FILE * fp;
    long int i, j, n, temp;

    printf("Enter array size:");
    scanf("%ld",&n);

    long int array[n];

    fp = fopen("5000averagecase.txt", "r");

    for (i=0; i < n; ++i)
        fscanf(fp,"%ld",&array[i]);

    for (i=0; i < n; ++i)
        for (j=0; j < n-1-i; ++j)
            if (array[j] > array[j+1]) {
                temp = array[j];
                array[j] = array[j+1];
                array[j+1] = temp;
                temp = 0;
            }

    for (i=0;  i< n; ++i)
        printf("%ld\t", array[i]);

    return(0);
}

https://i.stack.imgur.com/ZbxVU.png

因为你的文件只有从 15000 的值,而且我假设它们没有以任何方式排序,你为什么不制作另一个这样的文件

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

// shuffles an array given a pointer to the array and its length
void shuffleArray(int *array, int len) {
  srand(time(NULL));
  int n1, n2, tmp;
  for(int i = 1;i < len - 1; i++) {
    // get random two positions in the array to swap
    n1 = rand() % len, n2 = rand() % len;
    // just swap'em
    tmp = array[n1];
    array[n1] = array[n2];
    array[n2] = tmp;
  }
}

int main() {
  FILE * fp = fopen("5000averagecase.txt", "w");
  // check for file pointer validity
  if(fp == NULL) {
    printf("Error: can't open the file!");
    exit(0);
  }
  // creating an array of 5000 number
  int arr[5000];
  // fill it from 1 to 5000
  for(int i = 0;i < 5000; i++) {
    arr[i] = i + 1;
  }
  // shuffle it
  shuffleArray(arr, 5000);
  // write the array in `5000averagecase.txt` for later use
  for(int i = 0;i < 5000; i++) {
    fprintf(fp, "%d ", arr[i]);
  }
  // don't forget to close the file at the end
  fclose(fp);
  return 0;
}

现在执行此操作后,您将获得有效文件,并在其上执行排序代码后,您会看到它按预期工作