排序--快速排序

来源:互联网 发布:python sleep函数 编辑:程序博客网 时间:2024/05/19 03:46

快速排序的时间复杂度:O( nlogn ) 


C# 版

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace QuickSort{    class Program    {        static void Main(string[] args)        {            int[] arr = { 6, 7, 8, 4, 3, 2, 9, 1, 5 };            QuickSort(arr, 0, 8);            foreach (int i in arr)            {                Console.Write(i);            }            Console.ReadLine();        }        static void QuickSort(int[] arr, int l, int r)        {            int i = l;            int j = r;            int pivot = arr[(l + r) / 2];            while (i - j <= 0)            {                if (arr[i] < pivot)                    i++;                else if (arr[j] > pivot)                    j--;                else                {                        int temp = arr[i];                        arr[i] = arr[j];                        arr[j] = temp;                        i++; j--;                }            }            if (l < j)                QuickSort(arr, l, j);            if (r > i)                QuickSort(arr, i, r);        }    }}



C++ 版

// c++.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <vector>#include <iostream>using namespace::std;void QuickSort(vector<int>& vec, int l, int r){int i = l;int j = r;int pivot = vec[(l + r) / 2];while (i - j <= 0){if (vec[i] < pivot){++i;}else if (vec[j] > pivot){--j;}else{int tmp = vec[i];vec[i] = vec[j];vec[j] = tmp;++i;--j;}}if (l < j){QuickSort(vec, l, j);}if (i < r){QuickSort(vec, i, r);}}int _tmain(int argc, _TCHAR* argv[]){int arr[] = {6, 7, 8, 4, 3, 2, 9, 1, 5};vector<int> test(arr, arr + 9);QuickSort(test, 0, test.size() - 1);for (vector<int>::iterator iter = test.begin(); iter != test.end(); ++iter){cout << *iter << ", ";}getchar();return 0;}



C 版

// c.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"void QuickSort(int* arr, int l, int r){int i = l;int j = r;int pivot = arr[(j + i) / 2];while (i - j <= 0){if (arr[i] < pivot){++i;}else if (arr[j] > pivot){--j;}else{int tmp = arr[i];arr[i] = arr[j];arr[j] = tmp;++i; --j;}}if (l < j){QuickSort(arr, l, j);}if (i < r){QuickSort(arr, i, r);}}int _tmain(int argc, _TCHAR* argv[]){int arr[] = {9, 1, 5, 8, 7, 3, 4, 6, 2};int length = 9;QuickSort(arr, 0, length - 1);for (int i = 0; i < length; ++i){printf("%d, ", arr[i]);}getchar();return 0;}


0 0
原创粉丝点击