`
hongbochen1223
  • 浏览: 43799 次
文章分类
社区版块
存档分类
最新评论

C实现数组中元素的排序

 
阅读更多

使用C实现数组中元素的排序,使得数组中的元素从小到大排列。只不过在这个过程中出了一点小问题,在C中进行数字交换的时候,必须要使用指针的,不能使用引用。在后面的文章中,我要学习一个在C中的引用和指针的区别。下面看一下我的代码吧。

#include <stdio.h>

void swap(int *a,int *b);
void rest(int lels[],int count);

/**
 * 该实例用于实现对用户输入的数组进行排序
 * 要求的数组中的元素从小到大来咧
 *
 * @brief main
 * @return
 */
int main(void)
{
    /** 用于循环遍历的i **/
    int i = 0;

    /** 用于存储数组中元素的个数 **/
    int num;

    printf("Please enter the number of the array:\n");
    scanf("%d",&num);  //获取用户输入的数组元素的个数

    /** 用于存储用户输入的数组 **/
    int array[num];

    printf("Please enter the element of the array:\n");

    for(i = 0;i < num;i++)
        scanf("%d",&array[i]);

    rest(array,num);  //进行排序

    printf("The array after rest:\n");

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

    return 0;
}

/**
 * @brief swap 用于将元素a和元素b交换
 * @param a 要交换的数字a
 * @param b 要交换的数字b
 */
void swap(int *a,int *b){
    int temp = *a;
    *a = *b;
    *b = temp;
}

/**
 * @brief rest 用于对数组进行排序,从小到大排列
 * @param lels  要被排序的数组
 * @param count 被排序的数组元素的个数
 */
void rest(int lels[],int count)
{
    /** 暂时使用冒泡排序 **/
    /** 临时变量i,j **/
    int i,j;
    for(i = 0;i < count-1;i++){
        for(j = i+1; j < count;j++){
            if(lels[i] > lels[j])
                swap(&lels[i],&lels[j]);
        }
    }
}



<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>

版权声明:本文为博主原创文章,未经博主允许不得转载。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics