试图创建排序程序,但没有按预期工作

时间:2017-06-20 08:52:56

标签: c

以下代码用于排序数组 这个程序给出了意想不到的输出结果 错误应该在第10-19行。

#include<stdio.h>   //Sorting array program
int main()
{
    int arr[20],i,j,n,temp;
    printf("Enter number of elements  : ");
    scanf("%d",&n);
    printf("\nEnter the elements of the array : ");
    for (i=0;i<n;i++)
        scanf("%d",&arr[i]);
    for(i=0;i<n;i++)
    {
        for(j=0;j<arr[i];j++)
            if (arr[i+1]<arr[i])
            {
                temp=arr[i];
                arr[i]=arr[i+1];
                arr[i+1]=temp;
            }
    }
    printf("\nThe sorted list is : \n");
    for (i=0;i<n;i++)
        printf("\n arr[%d] : %d",i,arr[i]);
    return 0;
}

输出::          输入元素数量:4

     Enter the elements of the array : 5
     3
     2
     1

     The sorted list is : 

      arr[0] : 3
      arr[1] : 2
      arr[2] : 1
      arr[3] : -16777216
      Process returned 0 (0x0)   execution time : 8.161 s
      Press ENTER to continue.

2 个答案:

答案 0 :(得分:0)

修改你喜欢的程序,你就会发现会发生什么:

$.ajax({
            type: "GET",
            url: 'http://xxx?projectId='+projectId
            dataType:'json',
            contentType:"application/json",
            success:function(data){
                console.log(data.data);
                $(".photoprojectD").attr("src",data.data.projectPhotoUrl);
                $(".dlocation p").html(data.data.countryName);
                $(".dcategory p").html(data.data.categoryName);
 });

了解#include <stdio.h> //Sorting array program #include <assert.h> int main() { int arr[20], i, j, n, temp; printf("Enter number of elements : "); scanf("%d", &n); printf("\nEnter the elements of the array : "); for (i = 0; i<n; i++) scanf("%d", &arr[i]); for (i = 0; i<n; i++) { // <<< line added for (j = 0; j < arr[i]; j++) { assert(j < n); // <<< line added assert(i + 1 < n); // <<< line added if (arr[i + 1] < arr[i]) { temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } } // <<< line added } printf("\nThe sorted list is : \n"); for (i = 0; i<n; i++) printf("\n arr[%d] : %d", i, arr[i]); return 0; } here

但无论如何,算法对我来说看起来很可疑:

这条线特别可疑:

assert

答案 1 :(得分:0)

试试这个

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>   //Sorting array program

int main()
{
    int arr[20], i, j, n, temp;

    printf("Enter number of elements  : ");
    scanf("%d", &n);
    printf("\nEnter the elements of the array : ");
    for (i = 0; i<n; i++)
        scanf("%d", &arr[i]);

    for (i = 0; i<n; i++)
    {
        for (j = 0; j<n; j++)
            if (arr[i]<arr[j])
            {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
    }
    printf("\nThe sorted list is : \n");
      for (i = 0; i<n; i++)
         printf("\n arr[%d] : %d", i, arr[i]);
    printf("\n");

   return 0;
}