Hi Guys,
i was reading a book about C++ sorting and come up with the first type of sortting knowing as "Bubble-Sort" belwo is the main code for, you can run it and see how the arry will be ordred.

int main()
{
    int a[]={5,4,2,8,1,9,2,10,3,7,6};
    int i,j,temp;
    for(i=0;i<11;i++)
        cout<<a[i]<<" ";
    cout<<endl;


    for(i=0;i<10;i++)
        for(j=0;j<(10-i);j++)
                if(a[j]>a[j+1])
                {                
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
                }

    for(i=0;i<11;i++)
        cout<<a[i]<<" ";
    cout<<endl;

    getchar();
    return 1;
}

Howover, the book talked brefly about something called Selection -sort, can i one give me a example with code?

:lol:

Edited 3 Years Ago by Dani: Formatting fixed

main() returns 0 when no errors have occured.

Your implementation of the bubble sort won't work. Try this:

void sort_array(int *array, int len) {
    int did;

    do {
        did = 0;

        for(int x = 0; x < len; x ++) {
            for(int y = x+1; y < len; y ++) {
                if(array[y] < array[x]) {
                    int temp = array[x];
                    array[x] = array[y];
                    array[y] = temp;
                    did = 1;
                }
            }
        }
    }
}

main() returns 0 when no errors have occured.

Your implementation of the bubble sort won't work. Try this:

void sort_array(int *array, int len) {
    int did;

    do {
        did = 0;

        for(int x = 0; x < len; x ++) {
            for(int y = x+1; y < len; y ++) {
                if(array[y] < array[x]) {
                    int temp = array[x];
                    array[x] = array[y];
                    array[y] = temp;
                    did = 1;
                }
            }
        }
    }
}

Are you sure? it works with me fine...
i am still looking for selection and insertion code...

Are you sure? it works with me fine...
i am still looking for selection and insertion code...

Euhm, didn't look really well now did you :cheesy:

Eternally Confuzzled's Insertion sort

Try this Selection sort code in C++

int main()
{
    int a[]={5,4,2,8,1,9,2,10,3,7,6};
    int i,k,n,min;
    int temp;
for(i=0; i < n-1; i++)
 {
   min = i;
   for (k=i+1; k<n; k++)
     { 
       if (a[k] < a[min])
           min = k;
     }
   int temp = a[i];
   a[i]= a[min];
   a[min] = temp;
 } 
}

Edited 3 Years Ago by Dani: Formatting fixed

This article has been dead for over six months. Start a new discussion instead.