Zadanie 4

(ZS2021)zadanie04.cpp


PDF z cvičení (ZS 2021)

pt2021_bubblesort.pdf

pt2021_quicksort.pdf

Zdrojové súbory z cvičení (ZS 2021)

// Tema: Bubble sort
// Autor: Pavol Marak
// 19. 10. 2021

#include<iostream>

void printArray(const int *arr, const size_t n) {
    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}

void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

void bubbleSort(int *arr, const size_t n) {
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < n - i; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(&arr[j], &arr[j + 1]);
            }
        }
    }
}

int main() {
    int arr[] = {5,4,3,2,1};
    int n = sizeof(arr) / sizeof(arr[0]);
    printArray(arr, n);
    bubbleSort(arr, n);
    printArray(arr, n);
    return 0;
}
// Tema: Quick sort
// Autor: Pavol Marak
// 19. 10. 2021

#include <iostream>
#include <cstdlib>
#include <ctime>

void printArray(const int *arr, const size_t n) {
    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}

void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

// funkcia, ktora vrati index pivota ako nahodne vygenerovane cislo v intervale <low,high-1>
size_t getPivotIndex(const int *arr, const size_t low, const size_t high){
    return rand()%(high-low) + low;
}

// funkcia vykona partition tak, aby po vykonani:
//   * boli vlavo od pivota prvky mensie/rovne ako pivot
//   * boli vpravo od pivota prvky vacsie ako pivot
size_t partition(int *arr, const size_t pivot_index, const size_t low, const size_t high){
    swap(&arr[pivot_index],&arr[high-1]);
    int insert = low;
    for(size_t i = low;i<high;i++){
        if(arr[i] <= arr[high-1]){
            swap(&arr[i],&arr[insert++]);
        }
    }
    return insert-1;
}

// rekurzivna funkcia, ktora vykonava algoritmus Quick sort s cielom
// zotriedit pole vzostupne
void quickSort(int *arr, const size_t low, const size_t high){
    if(low+1 < high){
        size_t pivot_index = getPivotIndex(arr, low, high);
        pivot_index = partition(arr, pivot_index, low, high);
        quickSort(arr, low, pivot_index);
        quickSort(arr,pivot_index+1, high);
    }
}

// hlavna funkcia, ktora spusti rekurzivny Quick sort
void quickSort(int *arr, const size_t n){
    quickSort(arr, 0, n);
}

int main() {
    srand(time(NULL));
    int arr[] = {5,4,3,2,1};
    int n = sizeof(arr) / sizeof(arr[0]);
    printArray(arr, n);
    quickSort(arr, n);
    printArray(arr, n);
    return 0;
}