现在的位置: 首页 > 综合 > 正文

几种简单的排序算法

2017年12月22日 ⁄ 综合 ⁄ 共 1616字 ⁄ 字号 评论关闭

最近上班比较闲,试着写了快速排序、插入排序、希尔排序、选择排序 。

代码如下:

   //quickSort

        void QuickSort(int[] a,int s,int d)
        {

            if (s > d)
            {
                return;
            }

            int start = s;
            int end = d;
            int key = a[start];
        
            while (start < end)
            {
                while (start < end && a[end] >= key)
                {
                    end--;
                }
                a[start] = a[end];
 
                while (start < end && a[start] <= key)
                {
                    start++;
                }
                a[end] = a[start];
            }
            a[start]=key;
            QuickSort(a, s, start - 1);
            QuickSort(a, start+1, d);
           
           
        }

        // 冒泡排序
        void BubbleSort(int [] a, int n)
        {
            int temp = 0;
            for (int i = 1; i < n; i++)
            {
                for (int j = 0; j < n-i; j++)
                {
                    if (a[j] > a[j + 1])
                    {
                        temp = a[j];
                        a[j] = a[j + 1];
                        a[j + 1] = temp;
                    }
                }
            }
        }

        //插入排序
        void InsertSort(int[] a, int n)
        {
            int i = 0, j = 0, temp = 0;
            for ( i = 1; i < n; i++)
            {
                temp = a[i];
                for(j=i; j>0 && a[j-1]>temp ; j--)
                {
                    a[j] = a[j - 1];
                }
                a[j]=temp;
            }
        }

        //选择排序
        void SelectSort(int[] a, int n)
        {
            int temp = 0, sa = 0,j=0;
            for (int i = 0; i < n; i++)
            {
                temp = i;
                for ( j = i+1; j < n; j++)
                {
                    if (a[j] < a[temp])
                    {
                        temp = j;
                    }
                }
                sa = a[temp];
                a[temp] = a[i];
                a[i] = sa;
            }
        }

        //希尔排序
        void HellSort(int[] a, int n)
        {
            int i = 0, j = 0, temp = 0;
            for (int incr = n / 2; incr > 0; incr/=2)
            {
                for (i = incr; i < n; i ++)
                {
                    temp = a[i];
                    for (j = i; j >= incr && a[j - incr] > temp; j -= incr)
                    {
                        a[j] = a[j - incr];
                    }
                    a[j] = temp;
                }
             }
        }

抱歉!评论已关闭.