數組排序三種方法


方法一:交換排序  實現方法:把第一個位置的數字拿出來,依次合后面位置的數字比較,若比后面數字大,則交換

int[] str = new int[5] {237,5,88,1,101};
for (int i = 0; i < str.Length-1; i++)
{
  for (int j = i + 1; j < str.Length; j++)
  {
    if (str[i] > str[j])
    {
      int temp = str[i];
      str[i] = str[j];
      str[j] = temp;
    }
  }
}
for (int i = 0; i < str.Length; i++)
{
  Console.Write(str[i]);
  if(i<str.Length-1)
    Console.Write(",");
}

方法二:冒泡排序

for (int i = nums.Length - 1; i > 0; i--)
{
  //在 0-i 范圍內,將該范圍內最大的數字沉到i
  for (int j = 0; j < i; j++)
  {
    if (nums[j] > nums[j+1])
    {
      //交換
      int temp = nums[j];
      nums[j] = nums[j+1];
      nums[j+1] = temp;
    }
  }
}

方法三:選擇排序

for (int i = 0; i < nums.Length - 1; i++)
{
  //在 i-(nums.Length-1) 范圍內,將該范圍內最小的數字提到i
  //1. 首先找到 i - (nums.Length-1) 范圍內的最小數所在的下標
  int index = i; //先假設最小數的下標是i
  for (int j = i + 1; j < nums.Length; j++)
  {
    if (nums[j] < nums[index])
    {
      //發現了更小的數
      index = j;//記錄下標
    }
  }
  //2. 然后將nums[i]和nums[index]的值交換
  int temp = nums[i];
  nums[i] = nums[index];
  nums[index] = temp;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM