简体   繁体   English

在C程序中使用指针排序

[英]Sorting using pointers in C program

I written a sorting to an ascending order program using pointers in C.Logically this program works an ascending order,but output is descending order.What happened to this program. 我使用C语言中的指针编写了对升序程序的排序。从逻辑上讲,该程序按升序工作,但输出为降序。该程序发生了什么。

This is my code : 这是我的代码:

#include<stdio.h>
#include<stdlib.h>
main()
{
int n,i,j,t,*ptr,sum=0;
printf("Enter number of elements to sort : ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL)
{ printf("Error occurred memory not allocated \n"); exit(0);  }
printf("Enter the elements of Array \n");
for(i=0;i<n;i++)
{
scanf("%d",ptr+i);
}

for(i=0;i<n;i++){

       for(j=0;j<n;j++)
       {

           if( *(ptr+i) > *(ptr+j))
           {
               t = *(ptr+i);

               *(ptr+i) = *(ptr+j);
               *(ptr+j) = t;
           }
       }
}
for(i=0;i<n;i++)
{
printf("\n%d\n",*(ptr+i));
}

free(ptr);
}

Two things 两件事情

1) For ascending order, change the if statement to 1)对于升序,将if语句更改为

if( *(ptr+i) < *(ptr+j) )

2) You don't need to check the entire array every time. 2)您不需要每次都检查整个阵列。 You can start from the position of the previous lowest value. 您可以从上一个最小值开始。

for(i=0; i<(n-1); i++){
   for(j=i+1; j<n; j++) {
      ...
   }
}

OK let's do it step by step by a testcase that reproduces the "error". 好吧,让我们逐步通过一个再现“错误”的测试用例来做。

Suppose that the size of the array is 5, and the user input is 5, 3, 4, 2, 0 , so we have after iniliazization: 假设数组的大小为5,并且用户输入为5、3、4、2、0,那么在初始化之后,我们得到:

a[0]=5;
a[1]=3;
a[2]=4;
a[3]=2;
a[4]=0;

1) i = 0 ,j = 0 : (5 is not > 5) so no change
2) i = 0, j = 1 : (5 is > than 3) so a[0] -> 3 , a[1] -> 5
3) i = 0, j = 2 : (3 is not > 4) so no change
4) i = 0, j = 3 : (3 is > than 2) so a[0] -> 2 , a[3] -> 3
5) i = 0, j = 4 : (2 is > than 0) so a[0] -> 0 , a[4] -> 2

Now i=1;

1) i = 1, j = 0 : (5 is > than 0) so a[1] -> 0 , a[0] -> 5

You see, that you write a[0] = 5 again. 您会看到,您再次写入了[0] = 5。 This is the main error of your algorithm. 这是算法的主要错误。 If bubbleshort is what you want to implement have a better look at the algorithm (and after that check some more effective sorting algorithms like quicksort . 如果您想实现bubbleshort,则可以对算法进行更好的了解(然后检查一些更有效的排序算法,例如quicksort

your program is correct but the line: 您的程序是正确的,但行:

if( *(ptr+i) > *(ptr+j))

makes the arrangement in descending order, just make that line: 按降序排列,只需完成以下行:

if( *(ptr+i) < *(ptr+j)) 

and the output will be in ascending order. 并且输出将按升序排列。

I think you are trying to implement Bubble Sort. 我认为您正在尝试实施冒泡排序。 There is a logical problem in the code in second for loop 第二个for循环代码中存在逻辑问题

for(j=0;j<n;j++)

Change it to 更改为

for(j=1;j<n-1;j++). 

I think this will fix the issue 我认为这可以解决问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM