Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

Why are the array elements changed after sort,C

The elements of the array changed, and became some numbers which are never being input.

#include <stdlib.h>
#include <string.h>

#define MAX_SIZE 1000

int cmp(int a, int b)
 {
  return a>b;
 }

void sort(int *data, int n, int (*cmp)(int, int))
{
 for (;n>1;n--)
{
  int i_max = 0;
  for(int i = 1;i<n;i++)
   if(cmp(data[i],data[i_max])) i_max = i;

 int temp = data[i_max];
 data[i_max] = data[n-1];
 data[n-1] = temp;
 }
}


int main()
{
 int data[MAX_SIZE] , n;
 scanf("%d",&n);
 for(int i = 0 ; i < n ; i++)
 {
    int m;
    puts("*****************");
    scanf("%d",&m);
    for(int j = 0 ; j < m ; j++)
        scanf("%d",data+j);
    sort(data, m, cmp);
    puts("after sorting:");
    for(int j = 0 ; j < m ; j++)
    {
        printf("%d ",data[j]);
    }
    puts("
*****************");
}

return 0;
}

input:

5
5
12
346
5676434535
765654543596
3543456
6
5783945
5293
237894
273894
73
237482
4
27895
719287349723947
1
34
7
3472893
74897598347
757
178
579875498234
129
84
5
420938
23
837485
279
29871

output:

*****************
after sorting:
12 346 3543456 1150364908 1381467239
(the last two numbers were never input before, and the former number disappeared) 
*****************
*****************
after sorting:
73 5293 237482 237894 273894 5783945 
*****************
*****************
after sorting:
1 34 27895 586728235 
*****************
*****************
after sorting:
84 129 178 757 3472893 54913274 1883154315 
*****************
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The input you provide is not fitting into int. For example 765654543596 (hex B244912CEC) is exceeding 32 bits, which is probably your int width. If you truncate it to 32 bits you will see exactly the mysterious 1150364908 (hex 44912CEC) you see in the output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...