关于一个排序的问题
声明一个一维数组,大小为5,并分别用冒泡排序和选择排序实现排序,在java中实现,高手帮帮忙!!!!
------解决方案--------------------
------解决方案--------------------冒泡
public class bubbleSort {
public static void cubbleSort(int[] num){
int t;
for(int i=0;i<num.length-1;i++){
for(int j=0;j<num.length-i-1;j++){
if(num[j]>num[j+1]){
t=num[j];
num[j]=num[j+1];
num[j+1]=t;
}
}
}
}
public static void main(String args[]){
int[] n={1,2,3,5,13};
cubbleSort(n);
for(int a=0;a<n.length;a++)
System.out.println(n[a]);
}
}
------解决方案--------------------选择排序
public class SelectionSort {
public static void selectionSort(int[] number){
int t;
for(int i=0;i<number.length-1;i++){
int m=i;
for(int j=i+1;j<number.length;j++){
if(number[m]>number[j]){
m=j;
}
}
if(i!=m){
t=number[i];
number[i]=number[m];
number[m]=t;
}
}
}
public static void main(String args[]){
int[] num={12,5,28,42,182};
selectionSort(num);
for(int i=0;i<num.length;i++){
System.out.println(num[i]);
}
}
}
------解决方案--------------------public class SelectionSort {
private int[] data;
SelectionSort (int[] data){
this.data = data;
}
//算法主体内容
public void selectionSort(){
int index;
for(int i = 0; i < data.length; i++){
index = 0;
//找到最大值所在的位置
for(int j = 0; j < data.length-i; j++){
if(data[j] > data[index]){
index = j;
}
}
//交换数据
int tem = data[index];
data[index] = data[data.length-1-i];
data[data.length-1-i] = tem;
}
}
public void display(){
for(int i = 0; i< data.length; i++){
System.out.print(data[i] + " ");
}
System.out.println();
}
public static void main(String[] args){
int[] data = new int[]{67,12,32,43,55,33,54,65,43,22,66,98,74};
SelectionSort sort = new SelectionSort(data);
sort.display();
sort.selectionSort();
sort.display();
}
}
[size=12px]
选择排序[/size]
------解决方案--------------------觉得一楼的比较清晰
------解决方案--------------------Java code
public class Test {
public static void main(String[] args) {
int[] m = { 2, 8, 43, 3, 33 };
int[] n = sort(m);
for (int i = 0; i < m.length; i++) {
System.out.print(n[i] + " ");
}
}
/* 选择排序算法 */
public static int[] sort(int[] m) {
int intLenth = m.length;
int i,j,k,temp;
for (i=0; i < intLenth-1; i++) {
k = i;
for (j=i+1; j < intLenth ; j++) {
if(m[j] < m[k])k = j;
}
if(k != i) {
temp = m[i];
m[i] = m[k];
m[k] = temp;
}
}
return m;
}
}