码迷,mamicode.com
首页 > 编程语言 > 详细

C实现数组中元素的排序

时间:2015-04-24 09:04:20      阅读:167      评论:0      收藏:0      [点我收藏+]

标签: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]);
        }
    }
}



C实现数组中元素的排序

标签:c   数组   排序   数字交换   

原文地址:http://blog.csdn.net/hongbochen1223/article/details/45237865

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!