目录
本文为排序算法-快速排序的代码实现。
作者水平比较差,有错误的地方请见谅。
1、快速排序
冒泡排序属于交换排序。
平均时间复杂度:O(n*logn)
空间复杂度:
最坏:O(logn)
最好:O(n)
2、C#实现
QuickSort.cs
public static class QuickSort
{
public static void Quick(int[] numbers)
{
if (numbers == null || numbers.Length < 2)
{
Console.WriteLine("参数数组有误");
return;
}
QSort(numbers, 0, numbers.Length-1);
}
public static void QSort(int[] numbers,int low,int high)
{
if (low < high)
{
int index = Partition(numbers, low, high);
//对左右子表进行递归排序
QSort(numbers, low, index - 1);
QSort(numbers, index + 1, high);
}
}
public static int Partition(int[] numbers, int low, int high)
{
int temp = numbers[low];
while (low < high)
{
//比temp小的移动到左边
while (low < high && numbers[high] >= temp)
{
high--;
}
numbers[low] = numbers[high];
//比temp大的移动到右边
while (low < high && numbers[low] <= temp)
{
low++;
}
numbers[high] = numbers[low];
}
numbers[low] = temp;
return low;
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
int[] numbers = { 49, 38, 65, 97, 76, 13, 27, 49 };
QuickSort.Quick(numbers);
for (int i = 0; i < numbers.Length; i++)
{
Console.Write(numbers[i] + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
3、C++实现
.cpp
///直接插入排序
class QuickSort
{
public:
static void Quick(int numbers[],int low,int high);
static void QSort(int numbers[],int low,int high);
static int Partition(int numbers[],int low,int high);
};
void QuickSort::Quick(int numbers[],int low,int high)
{
if (numbers == NULL || (high+1) < 2)
{
cout<<"参数数组有误"<<endl;
return;
}
QSort(numbers,low,high);
}
void QuickSort::QSort(int numbers[],int low,int high)
{
if(low < high){
int index = Partition(numbers,low,high);
QSort(numbers,low,index-1);
QSort(numbers,index+1,high);
}
}
int QuickSort::Partition(int numbers[],int low,int high)
{
int temp = numbers[low];
while(low < high){
while(low < high && numbers[high]>=temp){
high--;
}
numbers[low] = numbers[high];
while(low < high && numbers[low]<=temp){
low++;
}
numbers[high] = numbers[low];
}
numbers[low] = temp;
return low;
}
main.cpp
int main()
{
int numbers[] = {49,38,65,97,76,13,27,49};
int length = sizeof(numbers)/sizeof(numbers[0]);
QuickSort::Quick(numbers,0,length - 1);
for(int i=0;i<length;i++){
cout<<numbers[i]<<" ";
}
cout<<endl;
return 0;
}
4、lua实现
numbers = {49,38,65,97,76,13,27,49}
length = #numbers
function QuickSort(nums,low,high)
if(low < high) then
local index = Partition(nums,low,high)
QuickSort(nums,low,index - 1)
QuickSort(nums,index + 1,high)
end
end
function Partition(nums,low,high)
local temp = nums[low]
while(low < high) do
while(low < high and nums[high] >= temp) do
high = high - 1
end
nums[low] = nums[high]
while(low < high and nums[low] <= temp) do
low = low + 1
end
nums[high] = nums[low]
end
nums[low] = temp
return low
end
QuickSort(numbers,1,length)
for i=1,length,1 do
io.write(numbers[i] .. ' ')
end
print()