// 演算法.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include <iostream>#include <ctime>using namespace std;void QuickSort(int e[], int first, int end);int _tmain(int argc, _TCHAR* argv[]){srand(unsigned(time(NULL)));//set 種子int t_nArray[10];//產生隨即數組for(int i = 0; i < 10; i++){t_nArray[i] = rand()%100;}//快速排序 QuickSort(t_nArray, 0, 9);//顯示數組for(int i = 0; i < 10; i++){cout << t_nArray[i] ;cout << "," ;}system("pause");return 0;}void QuickSort(int e[], int first, int end){int i=first,j=end;int temp=e[first];//記錄第一個資料while(i<j) {while(i<j && e[j]>=temp)//與first資料比較,右邊下標逐漸左移j--;e[i]=e[j];while(i<j && e[i]<=temp)//與first資料比較,左邊下標逐漸右移i++;e[j]=e[i]; }e[i]=temp;//將first資料放置於i=j處if(first<i-1)QuickSort(e,first,i-1);if(end>i+1)QuickSort(e,i+1,end);}
鏈表 快排
void list::PriorSort(node* &head, node* &end){ node *head1, *head2, *end1, *end2; //記錄每次分割後前後兩個鏈表的頭尾節點 head1 = head2 = end1 = end2 = NULL; if( head == NULL ) return; //如果遍曆的當前節點為空白,返回 node *p, *pre1, *pre2; //用於遍曆鏈表將鏈表中的元素分成大於key和小於key兩個部分 p = pre1 = pre2 = NULL; int key = head->priority; p = head->nextNode; head->nextNode = NULL; //將head的值孤立出來 while( p != NULL ) { //小於key的鏈表 if ( p->priority < key ){ if( !head1 ) { head1 = p; pre1 = p; } else{ pre1->nextNode = p; pre1 = p; } p = p->nextNode; pre1->nextNode = NULL; } //大於等於key的鏈表 else { if( !head2 ) { head2 = p; pre2 = p; } else { pre2->nextNode = p; pre2 = p; } p = p->nextNode; pre2->nextNode = NULL; } } end1 = pre1; end2 = pre2; //產生新鏈表的首尾節點 //對左右兩個鏈表進行遞迴快排 PriorSort(head1, end1); PriorSort(head2, end2); //從遞迴棧返回的時候,將key節點和左右兩個鏈表連起來 //左右鏈表都存在 if( end1 && head2) { end1->nextNode = head; head->nextNode = head2; head = head1; end = end2; } //只有左鏈表 else if(end1) { end1->nextNode = head; end = head; head = head1; } //只有右鏈表 else if(head2) { head->nextNode = head2; end = end2; }}