# 易混的排序算法：冒泡排序、选择排序、快速排序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Simple
{
class Program
{
static void Main(string[] args)
{
int[] data = new Int32[]{ 2, 3, 6, 8, 4, 5, 7 };
QuickSort(data, 0, data.Length - 1);
for (int i = 0; i < data.Length; i++)
{
Console.Write(data[i]+" ");
}
Console.WriteLine();

BubbleSort(data);
for (int i = 0; i < data.Length; i++)
{
Console.Write(data[i] + " ");
}
Console.WriteLine();

SelectSort(data);
for (int i = 0; i < data.Length; i++)
{
Console.Write(data[i] + " ");
}
Console.WriteLine();

}

/// <summary>
/// 冒泡排序
/// </summary>
/// <param name="data"></param>
static void BubbleSort(int[] data)
{
bool exchange=true;
for (int i = 0;(i < data.Length-1)&&(exchange==true); i++) //最多做R.Length-1趟排序
{
exchange = false; //本趟排序开始前，交换标志应为假
for (int j =0; j < data.Length -i-1; j++)
{
if (data[j + 1] < data[j])　//交换条件
{
int temp = data[j + 1];
data[j + 1] = data[j];
data[j] = temp;

exchange = true; //发生了交换，故将交换标志置为真
}
}
}
}
/// <summary>
/// 选择排序
/// </summary>
/// <param name="data"></param>
static void SelectSort(int[] data )
{
for(int i = 0;i < data.Length - 1;i++)
{
for (int j = i + 1; j < data.Length; j++)
{
if (data[j] < data[i])
{
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}

}

/// <summary>
/// 快速排序函数
/// </summary>
/// <param name="data"></param>
/// <param name="low"></param>
/// <param name="high"></param>
static void QuickSort(int[] data, int low, int high)
{
//设置中间值
int middle = data[(low + high) / 2];
int i = low;
int j = high;
//完成一次快速排序
do
{
//两侧向中间扫描
while (data[i] < middle && i < high)
i++;
while (data[j] > middle && j > low)
j--;
//找到可交换值
if (i <= j)
{
int temp = data[i];
data[i] = data[j];
data[j] = temp;
//交换后继续扫描
i++;
j--;
}

} while (i <= j);
//递归调用
if(j>low)
{
QuickSort(data, low, j);
}
if(i<high)
{
QuickSort(data, i, high);
}
}

}
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客