Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.8 kB
8
Indexable
Never
#include <iostream>
#include <conio.h>

using namespace std;
#define MAX 10

void swap(int *a, int *b){
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
void viewData(int *arr){
    for (int i = 0; i <MAX ; ++i) {
        if(i == MAX-1){
            cout<<arr[i];
        }else{

        cout<<arr[i]<<"-";
        }

    }
    cout<<endl;
}
void bubbleSort(int *arr) {
    cout<<"bubble sort"<<endl;
    cout<<"---------------------"<<endl;
    cout<<"Nilai awal : "<<endl;
    viewData(arr);
    cout<<"---------------------"<<endl;
    for (int i = 0; i < MAX - 1; i++) {
        for (int j = 0; j < MAX - i - 1; j++) {
            if (arr[j] > arr[j+1]) {
                swap(arr[j], arr[j + 1]);
                viewData(arr);
            }
        }
    }
}
void insertSort(int *arr){
    cout<<"Insert sort"<<endl;
    cout<<"---------------------"<<endl;
    cout<<"Nilai awal : "<<endl;
    viewData(arr);
    cout<<"---------------------"<<endl;
    for (int i = 1; i <MAX ; i++) {
        int j = i;
        while (j > 0 && arr[j-1] > arr[j]){
            swap(arr[j], arr[j-1]);
            j--;
            viewData(arr);
        }
    }
}
void selectionShort(int *arr){
    cout<<"Selection sort"<<endl;
    cout<<"---------------------"<<endl;
    cout<<"Nilai awal : "<<endl;
    viewData(arr);
    cout<<"---------------------"<<endl;
    for (int i = 0; i <MAX-1 ; i++) {
        int iMin = i;

        for (int j = i+1 ; j <MAX ; j++) {
            if (arr[j]< arr[iMin]){
                iMin = j;
            }
        }
        if (iMin != i){
            swap(arr[i], arr[iMin]);
        }
        viewData(arr);
    }
}
void insertData(int *dataArr){
    cout << "Masukkan " << MAX << " elemen array: "<<endl;
    for (int i = 0; i < MAX; i++) {
        cout<<"masukan data ke "<<i+1<<" : ";
        cin >> dataArr[i];
    }
    cout<<"tekan apa saja untuk lanjut...";
}
int main(){
    int arr[MAX];
    int choose;
    do{
    cout<<"===Sorting==="<<endl;
    cout<<"1. Insert Data "<<endl;
    cout<<"2. Insert Sort "<<endl;
    cout<<"3. Selection Sort"<<endl;
    cout<<"4. Bubble Sort "<<endl;
    cout<<"5. EXIT "<<endl;
    cout<<"Masukan Pilihan : ";
    cin>>choose;
        switch (choose) {
            case 1:
                insertData(arr);
                break;
            case 2:
                insertSort(arr);
                break;
            case 3:
                selectionShort(arr);
                break;
            case 4:
                bubbleSort(arr);
                break;
            default:
                getch();
                break;
        }
        getch();
        system("cls");
    } while (choose != 5);
    return 0;
}
Leave a Comment