用c語言實現冒泡排序,選擇排序,快速排序

來源:互聯網
上載者:User

代碼如下所示:
複製代碼 代碼如下:/*
* 冒泡排序
*/
void BubbleSort(int arr[], int n)
{
int temp;
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
/*
* 選擇排序
*/
void ChooseSort(int arr[], int n)
{
int temp, k;
for (int i = 0; i < n - 1; i++)
{
k = i;
for (int j = i + 1; j < n; j++)
{
if (arr[k] > arr[j])
{
k = j;
}
}
if (k != i)
{
temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
}
}
/*
* 快速排序,官方原版
*/
void q_sort(int numbers[], int left, int right)
{
int pivot, l_hold, r_hold;
l_hold = left;
r_hold = right;
pivot = numbers[left];
while (left < right)
{
while ((numbers[right] >= pivot) && (left < right))
{
right--;
}
if (left != right)
{
numbers[left] = numbers[right];
left++;
}
while ((numbers[left] <= pivot) && (left < right))
{
left++;
}
if (left != right)
{
numbers[right] = numbers[left];
right--;
}
}
numbers[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left < pivot)
{
q_sort(numbers, left, pivot-1);
}
if (right > pivot)
{
q_sort(numbers, pivot+1, right);
}
}
/*
* 快速排序
*/
void quick_sort(int *x, int low, int high)
{
int i, j, t;
if (low < high) /*要排序的元素起止下標,保證小的放在左邊,大的放在右邊。這裡以下標為low的元素為基準點*/
{
i = low;
j = high;
t = *(x+low); /*暫存基準點的數*/
while (i<j) /*迴圈掃描*/
{
while (i<j && *(x+j)>t) /*在右邊的只要比基準點大仍放在右邊*/
{
j--; /*前移一個位置*/
}
if (i<j)
{
*(x+i) = *(x+j); /*上面的迴圈退出:即出現比基準點小的數,替換基準點的數*/
i++; /*後移一個位置,並以此為基準點*/
}
while (i<j && *(x+i)<=t) /*在左邊的只要小於等於基準點仍放在左邊*/
{
i++; /*後移一個位置*/
}
if (i<j)
{
*(x+j) = *(x+i); /*上面的迴圈退出:即出現比基準點大的數,放到右邊*/
j--; /*前移一個位置*/
}
}
*(x+i) = t; /*一遍掃描完後,放到適當位置*/
quick_sort(x,low,i-1); /*對基準點左邊的數再執行快速排序*/
quick_sort(x,i+1,high); /*對基準點右邊的數再執行快速排序*/
}
}
// 輸出數組元素
void outArray(int arr[], int n)
{
for(int i = 0; i < n; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
void main()
{
const int N = 5;
int arr1[N] = {4, 3, 5, 2, 1};
int arr2[N] = {4, 3, 5, 2, 1};
int arr3[N] = {4, 3, 5, 2, 1};
cout<<"Before bubble sort"<<endl;
outArray(arr1, N);
BubbleSort(arr1, N);
cout<<"After bubble sort"<<endl;
outArray(arr1, N);
cout<<"/nBefore chooose sort"<<endl;
outArray(arr2, N);
ChooseSort(arr2, N);
cout<<"After chooose sort"<<endl;
outArray(arr2, N);
cout<<"/nBefore quick sort"<<endl;
outArray(arr3, N);
//q_sort(arr3,0, N - 1);
quick_sort(arr3,0, N - 1);
cout<<"After quick sort"<<endl;
outArray(arr3, N);
system("pause");
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.