有1,2,3一直到n的無序數組,排序


題目:有1,2,3,..n 的無序整數數組,求排序算法。要求時間復雜度 O(n), 空間復雜度O(1)。

分析:對於一般數組的排序顯然 O(n) 是無法完成的。 既然題目這樣要求,肯定原先的數組有一定的規律,讓人們去尋找一種機會。

例如:原始數組: a = [ 10, 6,9, 5,2, 8,4,7,1,3 ] ,如果把它們從小到大排序且應該是 b = [1,2,3,4,5,6,7,8,9,10 ],也就是說: 如果我們觀察 a --> b 的對映關系是: a[i] 在 b 中的位置是 a[i] - 1,即a[i]=b[a[i]-1]

代碼:

#include<iostream>
#include<ctime>
using namespace std;
void print(int* a, int n){
    for (int i = 0; i < n; i++){
        cout << a[i] << ",";
    }
    cout << endl;
}
void FancySort(int* a, int n){ int temp; int swapCount = 0; for (int i = 0; i < n;) { swapCount++; //a[i]-1為a[i]在有序數組中的位置 //因此a[i]與a[a[i]-1]交換后,a[i]就處於正確位置了 //但交換后的a[a[i]-1]不一定處於正確位置 temp = a[a[i] - 1]; a[a[i] - 1] = a[i]; a[i] = temp; cout << "" << swapCount << "次交換 " << "i=" << i << endl; print(a, n); //直到第i位也有了正確的數字,開始處理下一位 if (a[i] == i + 1) i++; } } int main(){ while (true){ cout << "輸入n:" << endl; int n; cin >> n; int* a = new int[n]; for (int i = 0; i < n; i++){ a[i] = 0; } //對數組(1,2,....一直到n的無序數組)賦予初始化隨機值 srand(time(0)); for (int i = 1; i <= n;){ int randV = rand() % n; if (a[randV] == 0){ a[randV] = i; i++; } } cout << "the input array:"; print(a, n); FancySort(a, n); cout << "排序結果:"; print(a, n); cout << endl; } return 0; }

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM