基于插入排序的表排序

具体知识点请去中国大学MOOC看浙大版数据结构,这里只给出了算法的实现。

#include<bits/stdc++.h>
using namespace std;

/*
    表排序:
        之前的排序中我们是直接对数据进行交换来进行排序。适用于数据项的sizeof()较小时, 
        但是对于数据项的sizeof()较大时,直接交换数据项太浪费时间,表排序便是解决这个问题的。

    思想:
        定义一个表存储每个数据项的真实位置,输出的时候输出arr[pos[0]], arr[pos[1]] ... 

    物理排序:
        对于必须直接把数据排序的情况,进行完表排序后可以在线性时间复杂度内完成物理排序 

    下面实现的是基于插入排序的表排序  、 升序排序 
*/

int* tableSort(int *arr, int len)
{
    int *pos = new int[len];
    for(int i = 0; i < len; i++)
        pos[i] = i;
    for(int i = 1; i < len; i++)
    {
        int temp = arr[i], j, tp = pos[i];
        for(j = i - 1; j >= 0 && arr[pos[j]] > temp; j--)
            pos[j + 1] = pos[j];
        pos[j + 1] = tp;
    }
    return pos;
}

void tableSortCastToPhysicalSort(int *arr, int *pos, int len)
{
    for(int i = 0; i < len; i++)
    {
        if(pos[i] != i)
        {
            int temp = arr[i];          
            int j = i, k = i;           
            while(pos[k] != j)          
            {
                arr[k] = arr[pos[k]];
                int t = pos[k];
                pos[k] = k;
                k = t;
            }
            arr[k] = temp;
            pos[k] = k;
        }
    }
} 
int main()
{
    int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
//  int arr[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
//  int arr[10] = {8, 1, 4, 9, 0, 3, 5, 2, 7, 6};
    int *pos = tableSort(arr, 10);
    for(int i = 0; i < 10; i++)
        cout << arr[pos[i]] << " ";
    cout << endl;
    tableSortCastToPhysicalSort(arr, pos, 10);
    for(int i = 0; i < 10; i++)
        cout << arr[i] << " ";
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_38206090/article/details/82353271