Common algorithms
1. Bubbling algorithm
(1). Basic ideas
Adjacent elements of the two comparisons, large back surface, after the first comparison, the maximum is now the largest index, the same kind of comparison several times, so that you can get a well-ordered
Array.
(2). Program Flow Design
A: The two compare, the data big back put
B: After the first comparison is complete, the next comparison will reduce one element.
C: The first comparison has 0 elements not participating in the comparison
The second comparison has 1 elements that do not participate in the comparison
The third comparison has 2 elements that do not participate in the comparison
.....
Nth comparison with n-1 elements not participating in the comparison
D: Total number of comparisons required: array Length-1 times
(3). Code implementation
Public class Test {
public static void Main (string[] args) {
//define Data source
Int[] arr={12,23,4,53,32,123,23,23,78} ;
if (arr.length>0) {
Bubblesort (arr);
PrintArray (arr);
}
}
/**
* Bubble sorting algorithm
* @param int[] Arr: Data source
* @author Administrator
*/
public static void Bubb Lesort (int[] arr) {
for (int. i=0;i<arr.length;i++) {
for (int j=0;j<arr.length-1-i;j++) {
if (arr[j]> Arr[j+1]) {
int temp=arr[j];
ARR[J]=ARR[J+1];
Arr[j+1]=temp;
}
}
}
/**
* Iterate array display output
* @author Administrator
* @param int[] Data source to output
*/
Public static void PrintArray (int[] arr) {
System.out.print ("{");
for (int i=0;i<arr.length;i++) {
if (i==arr.length-1) {
System.out.print (arr[i]);
} else{
System.out.print (arr[i]+ ",");
}
}
System.out.print ("}");
}
}
//output result
{4,12,23,23,23,32,53,78,123}
(5). Examples of actual use
A: Requirements: Input string "DASDFHASASJDFH"
Output string ""
The real thing is to sort the strings in order.
B: Code Analysis
A. Defining a string
B. Converting a string to a character array (ToCharArray ())
C.b to sort the array
D. Turning a sorted character array into a string
E. Output the last character
C. Code implementation
public class Test {
public static void Main (string[] args) {
Defining a data source string
String str= "DASDFHASASJDFH";
Convert a defined string into a character array
Char[] Chs=str.tochararray ();
Sort a character array
Bubblesort (CHS);
Turns the sorted character array into a string
String result=string.valueof (CHS);
Output the final result
SYSTEM.OUT.PRINTLN ("result is:" +result);
}
/**
* Bubble Sorting algorithm
* @param int[] Arr: Data source
* @author Administrator
*/
public static void Bubblesort (char[] arr) {
for (int i=0;i<arr.length;i++) {
for (int j=0;j<arr.length-1-i;j++) {
if (Arr[j]>arr[j+1]) {
Char Temp=arr[j];
ARR[J]=ARR[J+1];
Arr[j+1]=temp;
}
}
}
}
}
The output is:
Result Is:aaadddffhhjsss
Java Basic algorithm 1: Bubbling algorithm