c - 排序整数数组 C

标签 c arrays sorting pointers

<分区>

我是一名学习计算机科学的初学者 c 程序员,我正在尝试创建一个排序程序来对整数数组进行排序,尽管我总是得到错误的结果,这是我到目前为止所得到的:

#include <stdio.h>
#include <string.h>    
#define TAM 9

int sort_array(int num1[],int num2[]);    
int main(){
    int i=0;   
    int num1[TAM] = {5,6,2,4,7,1,3,0};
    int num2[TAM] = {0};
    int * ptr_num2 = num2;

    sort_array(num1,num2);

    while(*ptr_num2 != '\0'){
        printf("%c",*ptr_num2+48);
        ptr_num2++;
    }
    putchar('\n');

    return 0;
}

int sort_array(int num1[],int num2[]){
    int min=256,max=0,i,j;
    int * ptr_num1 = num1;
    int * ptr_max = num1;
    int * ptr_num2 = num2;

    /* check for max */
    while(*ptr_max != '\0'){
        if(*ptr_max > max) max = *ptr_max;
        ptr_max++;
    }

    for(i=0;i<TAM-1;i++){
        /* check for min */
        for(j=0;j<TAM-1;j++){
            if(*ptr_num1 < min) min = *ptr_num1;
            ptr_num1++;
            num1[i] = max;
        }
        *ptr_num2 = min;
        ptr_num2++;
    }
    return 0;
}

我已经为此苦苦思索了几个小时。

编辑:忘记提及其中一些事情可能没有意义,因为我只是在试验一些事情。

最佳答案

我知道你不知道典型的数组排序......好吧,让我向你介绍一种更简单的排序。虽然它通常不是最有效的一种,但它是最容易理解的一种,并且考虑到您处理的是小数组而不是数据库这一事实,它会很好。

我说的是好 friend ,我们的冒泡排序

冒泡排序是一种众所周知的简单数组排序算法 - 逻辑很简单。您以两个对的形式遍历整个数组 - 即,Array[0] 与 Array[1]、Array[1] 与 Array[2],等等...

每当你发现事情不是他们应该的样子 - 在你的情况下,较大的索引号大于较低的索引号 - 你在它们之间交换,直到你到达你通过整个的迭代数组,根本没有交换。

如果你不太理解,这里是来自维基百科的伪代码(天哪,他妈的使用维基百科,我真是个傻瓜):

procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat 
 swapped = false
 for i = 1 to n-1 inclusive do
   /* if this pair is out of order */
   if A[i-1] > A[i] then
     /* swap them and remember something changed */
     swap( A[i-1], A[i] )
     swapped = true
   end if
  end for
 until not swapped
end procedure

这是一些 C 代码:

#include <stdio.h>

int main()
{
int array[100], n, c, d, swap; 
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
  if (array[d] > array[d+1]) /* For decreasing order use < */
  {
    swap       = array[d];
    array[d]   = array[d+1];
    array[d+1] = swap;
    }
  }
}

printf("Sorted list in ascending order:\n");

for ( c = 0 ; c < n ; c++ )
 printf("%d\n", array[c]);

return 0;
}

顺便说一句,功劳不属于我: http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort

希望这对你有帮助,祝你好运:)

关于c - 排序整数数组 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28000990/

相关文章:

arrays - 使用 textFieldDidEndEditing 文本字段委托(delegate)查找数组中的 3 个元素

Java 对列表中的项目进行排名

python - Django:如何编写查询以使用多列进行排序,通过模板显示

c - C语言中的字符串输入问题

c - C 中的段错误和无限循环 - 自调用 main 函数

c++ - C/C++ : Size of builtin types for various compilers/platforms

javascript - 如何利用 JavaScript 和 ES5 从基于关键字段的对象数组中获取唯一值

javascript - 排序数组问题

javascript - 按另一个索引数组对数组进行排序

c++ - 将 dll 转换为 lib 以进行静态链接?