/*
* 题目描述:
* 给定一个数组m[7] = {5, 8, 9, 6, 7, 3, 2},将该数组中的元素按照从小到大的顺序排列,
* 输出排序后的数组;排序完成后,将元素4插入该数组中的正确位置,并输出插入后的数组。
*/
public class BubbleSort {
public static void main(String[] args) {
//被排序的数组——可任意添/删元素
int[] m = {5, 8, 9, 6, 7, 3, 2};
//使用冒泡排序排序数组中的元素
BubbleSort.bubbleSort(m, m.length);
//打印排序后的数组
System.out.print("排序后的数组 m[]:");
BubbleSort.prinfArray(m);
System.out.println();
//使用冒泡排序排序数组中的元素
BubbleSort.bubbleSortBetter(m, m.length);
//打印排序后的数组
System.out.print("优化排序后的数组 m[]:");
BubbleSort.prinfArray(m);
System.out.println();
//被插入的元素
int n = 4;
//向数组中插入数据
int r[] = BubbleSort.Insert(m, n);
//打印插入元素后的数组
System.out.print("插入4后的数组 m[]:");
BubbleSort.prinfArray(r);
}
/**
* 向原数组中插入一个元素构成一个新数组,并返回该新数组
*
* @param m:原数组
* @param n:被插入元素
* @return:插入元素后的新数组
*/
public static int[] Insert(int m[], int n) {
//新数组
int[] r = new int[m.length+1];
//遍历原数组m[],将原数组m[]中小于n的部分直接放入新数组r[]中;
//将元素n插入新数组m中,
//将原数组m[]中大于n的部分依次放入新数组r[]中
for(int i = 0; i < m.length; i++) {
//原数组m[]中小于n的部分直接放入新数组r[]中
if(m[i] < n) {
r[i] = m[i];
}
if(n < m[i]) {
//将元素n插入新数组r[]中
r[i] = n;
//将原数组r[]中剩余部分放入新数组r[]中
for(int j = i + 1; j < m.length + 1; j++) {
r[j] = m[j-1];
}
break;
}
}
return r;
}
/**
* 打印数组
*
* @param array:被打印的数组
*/
public static void prinfArray(int array[]) {
for(int a: array) {
System.out.print(a + " ");
}
}
/**
* 冒泡排序——一般冒泡排序算法
*
* @param array:被排序的数组
* @param n:被排序数组的长度
*/
public static void bubbleSort(int array[], int n) {
for(int i = 0; i < n-1; i++) {
for(int j = 0; j < n-1-i; j++) {
if(array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j+1];
array[j+1]=temp;
}
}
}
}
public static void bubbleSortBetter(int array[],int n) {
for(int i=0; i<n-1; i++) {
Boolean isSorted = true;
for(int j=0; j<n-1-i; j++) {
if(array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j+1];
array[j+1]=temp;
}
}
if(isSorted) break; //如果没有发生交换,说明数组已经排序好了
}
}
}
冒泡排序练习
最新推荐文章于 2025-05-26 14:39:16 发布