bubble sort swaping code example

Example: c++ buble sort

void bubbleSort(int arr[], int size){
  int temp = int();
  //print out the unsorted values
  for ( int i = 0; i < size -1; i ++)
    cout << arr[i] << "\t";
  cout << endl << endl;
  
  
  for (int i = 1; i < size; i++ ){
  	for(int j = 0; j < size - i ; j ++){//size-i is the sorted part of the array	
   		if( arr[j] > arr[j + 1]){//if the value is greater than the next value in the array, swap it
          temp = arr[j];
          arr[j] = arr[j+1];//swap the two values
          arr[j+1] = temp;
          
        }//end if
    }//end for
  }//end for
  
}//end bubbleSort

Tags:

Misc Example