sort (Bubble sort\ Selection sort\ Insertion sort

程式作業
 avatar
YTC
c_cpp
3 years ago
2.3 kB
5
Indexable
 //
//  main.cpp
//  codehomework #04
//
//  Created by YTC on 2022/3/23.
//
//selection sort
//insertion sort
//bubble sort

#include <iostream>

using namespace std;
void print_the_array(int *arr, int length){
    for(int i = 0 ; i < length ; i++){
        cout<< arr[i]<<" " ;
    }
    cout << endl;
}

void swap(int *xp , int *yp){
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

void insertion_sort(int *arr, int size){
    int i = 1, key = 0;
    for(i = 1; i < size ; i++)
    {
        key = arr[i];
        int j = i;
        while(j > 0 && arr[j-1] > key){
            {
                arr[j] = arr[j-1];
                j--;
            }
            arr[j] = key;
        }
    }
}


void selection_sort(int *arr, int size){
    int i, j, imin;
    for(i = 0 ; i < size-1 ; i++){
        imin = i;
        for(j = i + 1; j <size ; j++){
            if(arr[j] < arr[imin]){
                imin = j;
                swap(arr[i], arr[imin]);
            }
        }
    }
}


void bubble_sort(int arr[] , int size){
    int i, j;
    bool swapped;
    for(i =0 ; i < size ; i++){
        swapped = false;
        for(j = 0 ; j < size-i-1; j++){
            if( arr[j] >arr[j+1]){
                swap( &arr[j], &arr[j+1]);
                swapped = true;
            }
        }
        if(swapped == false){
            break;
        }
    }
}
int main(int argc, const char * argv[]) {
    int arr[10], arraysize=10;
    cout<<"Input the ten numbers into the array:";
    for(int i = 0; i < arraysize ; i++){
        cin>> arr[i];
    }
    cout << "Unsorted array: " <<endl;
    int length = sizeof(arr)/sizeof(arr[0]);//size of array with 9 values contains 9 integer. As we all know, the size of an integer is 4 bits. So, size of an array with 9 values equals to  9 times 4 bits equals to 36 bits. This is the way we get the length of an array.
    print_the_array(arr,length);
    bubble_sort(arr, length);
    cout<<"Bubble sorted array: "<< endl;
    
    for(int i = 0 ; i < length ; i++){
        cout<< arr[i]<<" " ;
    }
    cout << endl;
    insertion_sort(arr, length);
    cout << "Insertion Sorted array: " << endl;
    print_the_array(arr,length);
    cout << "Selection Sorted array: " << endl;
    print_the_array(arr, length);
    return 0;
}
Editor is loading...