算分与数据结构 - 冒泡思想

来源:互联网 发布:阿里云按量付费1g 编辑:程序博客网 时间:2024/06/01 10:42

冒泡思想的一个特点是所有的操作都在原数组中进行,不占用额外的空间。

一、冒泡排序

public class BubbleSort {    public void bubbleSort(int[] array) {int len = array.length;int temp;for (int i=0; i<len; i++) { // n趟越来越短的相邻位置的两两交换    for (int j=0; j<len-i-1; j++) { // 易错点 if (array[j] > array[j+1]) {     temp = array[j+1];    array[j+1] = array[j];    array[j] = temp;}    }}    }    public static void main(String[] args) {int[] array = {1, 9, 2, 8, 3, 7, 4, 6, 5};new BubbleSort().bubbleSort(array);for (int i=0; i<array.length; i++)    System.out.print(array[i] + " ");    }}

二、冒泡整理

<span style="font-size:18px;">/** * 问题:把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间。  * 输入例子:AkleBiCeilD * 输出例子:kleieilABCD *  * 思路 * 遍历字符数组,如果位置i是小写字母,则与位置i前的所有大写字母冒泡式两两交换。 * 这样不仅不会占用额外空间,且字母间的次序不会改变。 */public class PutUppercaseBehind {    public String putUppercaseBehind(String str) {char[] c = str.toCharArray(); // 转化为字符数组char temp;for (int i = 0; i < c.length; i++) {    if (c[i] >= 'a' && c[i] <= 'z') { // 寻找小写子母for (int j = i - 1; j >= 0; j--) { // 从i往前找大写字母    if (c[j] >= 'A' && c[j] <= 'Z') { // 发现一个大写字母就与c[i]两两交换temp = c[i];c[i] = c[j];c[j] = temp;i = j;            }}            }}        return String.valueOf(c); // 将字符数组通过String.valueof()转化为字符串    }    public static void main(String[] args) {        String str = "AkleBiCeilD";System.out.println(new PutUppercaseBehind().putUppercaseBehind(str));    }}</span>



0 0
原创粉丝点击