版權聲明:您好,轉載請留下本人部落格的位址,謝謝 https://blog.csdn.net/hongbochen1223/article/details/45237865
使用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]);
}
}
}