C++ array bubblesort

I am struggling with creating a bubblesort function , this is my array I need to sort from smallest to largest :


int array[10] = {1,2,3,4,5,6,7,8,9,10};

int main ()
{
int i;
for (i=0; i <10; i++)
{
printf("%d\n", array[i]);
}
system("pause");
return 0;
}


I know it's something to do with a loop inside another loop but can you help explain it to me and show me an example or use my array and sort it thankyou so much?
The idea is, if(array[i] > array[i+1]) swap(array[i], array[i+1]);
do it step be step:
1. Write a program which sorts the first two elements.
2. Write a program which goes through the array only once and (if necessary) swaps elements. (a for loop)
3. Put the second program, some output and a getchar() in a while(true) loop. See how the array is sorted.
4. If no swaps happen, the array is already sorted. When that happens, break form the while(true) loop of the third program.

If I recall correctly, there is some pseudocode in wikipedia, if you can't figure out the fourth one.
1
2
3
4
5
6
7
for (int k = 1; k < size; k++)
  for (int i = 0; i <size -1 - k; i++)
       if (a[i] > a[i +1]){
          int temp = a[i];
          a[i] = a[i + 1];
         a[i + 1] = temp;
      } 
If you want to know more about search algorithms i would suggest you go to youtube. There you could search for Richard Buckland. He is a professor at an Australian university.

He puts is lessons on youtube for everyone to watch. He is a great teacher, in one of his series he talks about a dozen of different search algorithms. Including the implementation, the time they need to run, pros and cons etc.

"Lecture 6: Data Structures and Algorithms - Richard Buckland" at this lesson he is already talking about other sorting algorithms. It has to be a lesson prior to this where he is describing bubble sort. Thus maybe you should search youtube for "Lecture 5: Data Structures and Algorithms - Richard Buckland"
Last edited on
@Darakthar:

What is the link?Let's look at us.
thanks Darokthar
Topic archived. No new replies allowed.