Home > database >  My sorting algorithm doesn't function due to unknown reason
My sorting algorithm doesn't function due to unknown reason

Time:10-29

I'm trying to create a sorting algorithm, it contains a nested loop which compares each element of the array to all other elements in the array, and if an element is greater in value than any of its succeeding elements, they switch places with each other. But for some reason my program won't output anything and exits with code 0, i.e. success.

Following is my code:

#include <iostream>
using namespace std;

void sortAlgo(int *a, int n){
    int tmp;
    for (int i=0; i<=n-1; i  ){
        for(int j=i 1; j<=n; j  ){ //O(n^2)
            if(a[i]>a[j]){
                //LHS variable assumes RHS quantity
                tmp=a[i]; //a[i] value stored in temp variable
                a[i]=a[j]; //shifts a[j] value to a[i]
                a[j]=tmp; //a[j] takes value of a[i]
            }
        }
    }
    for(int x=0; x<=n; x  ){
                cout<<a[x]<<" ";
            }
}

int main(){
    int arr[10]={1,2,3,5,23,12,4};
    sortAlgo(arr, 7);
}

I am using VS Code.

CodePudding user response:

It is not the bubble sort algorithm You are trying to implement the selection sort algorithm with redundant swaps.

These for loops

for(int j=i 1; j<=n; j  ){ //O(n^2)

and

for(int x; x<=n; x  ){

have invalid conditions that in general can result in undefined behavior if the passed array will have exactly n elements because the expression a[n] will access memory beyond the array..

Moreover in the second for loop the variable x was not initialized that again invokes undefined behavior.

Pay attention to that instead of to swap "manually" two elements

tmp=a[i]; //a[i] value stored in temp variable
a[i]=a[j]; //shifts a[j] value to a[i]
a[j]=tmp; //a[j] takes value of a[i]

you could use standard C function std::swap declared in the header <utility>.

  • Related