Bubble Sort is another classic embodiment of brute force law .
Algorithmic thinking: compare the adjacent elements in the list, and if they are in reverse order, swap their positions. Once repeated, the largest element is placed in the last position. The second pass moves the second element to the second-to-last position, so that it is kept in sequence until the entire list is n-1.
Here's My Code implementation: C + +
#include <iostream>using namespace Std;int main () { int i,j,temp,n; cin>>n; int *arr=new Int[n]; for (i=0;i<n;i++) cin>>arr[i]; for (i=0;i<n;i++) { for (j=0;j<n;j++)//compare { if (arr[j]>arr[j+1])//If reverse, swap { Temp=arr[j]; ARR[J]=ARR[J+1]; Arr[j+1]=temp ; }}} for (i=0;i<n;i++)//output cout<<arr[i]<< ""; return 0;}
Algorithm analysis: The size of the input is determined entirely by N, the basic operation is comparison: arr[j]>arr[j+1], time complexity C (n) =θ (n2).
But the number of times the key is exchanged depends on the particular input, and the worst case is the opposite of what we ordered, when the key is swapped = the number of times the key is =θ (N2).
However, in some cases, if the list is not swapped for the position of the element after it has been compared over and over again, then the list is in order and we can stop the algorithm. The specific improvement versions are as follows:
#include <iostream>using namespace Std;int main () { int i,j,temp,n; BOOL Change=false; cin>>n; int *arr=new Int[n]; for (i=0;i<n;i++) cin>>arr[i]; for (i=0;i<n;i++) { change=false; for (j=0;j<n;j++)//compare { if (arr[j]>arr[j+1])//If reverse, swap { temp=arr[j]; ARR[J]=ARR[J+1]; Arr[j+1]=temp; change=true; } } if (!change)//No swap occurs, then no further comparisons are necessary. {break ; } } for (i=0;i<n;i++)//output cout<<arr[i]<< ""; return 0;}
But in the worst case, the time complexity is θ (n2).
Brute force Method--bubble sort