(JAVA版)冒泡排序

时间:2022-10-17 16:53:38

核心代码:

public void bubbleSort(){
for(int i=;i<length-;i++){
for(int j=;j<length-i-;j++){
if(a[j]>a[j+])
swap(j,j+);
}
}
}
public void swap(int indexa,int indexb){
int temp = a[indexa];
a[indexa] = a[indexb];
a[indexb] = temp;
}

主要代码

class Array{
private int[] a;
private int length; public Array(int max){
a = new int[max];
length = ;
}
public void insert(int value){
a[length] = value;
length++;
}
public void dispaly(){
for(int i=;i<length;i++)
System.out.println("a["+i+"]="+a[i]);
}
public void bubbleSort(){
for(int i=;i<length-;i++){
for(int j=;j<length-i-;j++){
if(a[j]>a[j+])
swap(j,j+);
}
}
}
public void swap(int indexa,int indexb){
int temp = a[indexa];
a[indexa] = a[indexb];
a[indexb] = temp;
}
}
class haha{
public static void main(String[] args){
Array arr = new Array();
for(int i=;i<;i++){
arr.insert(-i);
}
arr.bubbleSort();
arr.dispaly();
}
}

执行示例

(JAVA版)冒泡排序