Untitled
unknown
c_cpp
4 years ago
2.8 kB
13
Indexable
#include <bits/stdc++.h>
using namespace std;
void Menu() {
cout <<"1.SelectionSort"<<"\n";
cout <<"2.BubbleSort"<<"\n";
cout <<"3.QuickSort"<<"\n";
cout <<"4.MergeSort"<<"\n";
cout <<"5.Heapsort"<<"\n";
}
void NhapMang(int a[], int n){
for(int i = 0; i < n; i++){
printf("\nNhap a[%d] = ",i);
scanf("%d", &a[i]);
}
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min])
min = j;
// Swap the found minimum element with the first element
swap(&arr[min], &arr[i]);
}
}
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int left = low;
int right = high - 1;
while(true){
while(left <= right && arr[left] < pivot) left++;
while(right >= left && arr[right] > pivot) right--;
if (left >= right) break;
swap(arr[left], arr[right]);
left++;
right--;
}
swap(arr[left], arr[high]);
return left;
}
/* Hàm thực hiện giải thuật quick sort */
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi là chỉ số nơi phần tử này đã đứng đúng vị trí
và là phần tử chia mảng làm 2 mảng con trái & phải */
int pi = partition(arr, low, high);
// Gọi đệ quy sắp xếp 2 mảng con trái và phải
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver program to test above functions
int main()
{
int a[100];
int n;
int choice;
printf("\nNhap so luong phan tu n = ");
do{
scanf("%d", &n);
if(n <= 0){
printf("\nNhap lai n = ");
}
}while(n <= 0);
NhapMang(a,n);
Menu();
do {
cout<<"lua chon cach sap xep (1-5):";
cin>>choice;
switch(choice){
case 1:selectionSort(a,n);break;
case 2:bubbleSort(a,n);break;
case 3:quickSort(a, 0, n-1);break;
}
cout << "Sorted array: \n";
printArray(a,n);
}while(choice<=0);
return 0;
}Editor is loading...