面试中常见的数据结构与算法

第二章排序

2.1 O(n2) 算法

给定一数组,其大小为8个元素,数组内的数据无序。

6 3 5 7 0 4 1 2

  • 冒泡排序:两两比较,将两者较少的升上去,第一次比较空间为0-(N-1)直到最后一轮比较空间为0-1
public class bubbleSort {

    public static void main(String[] args) {
        int[] test = { 6, 3, 5, 7, 0, 4, 1, 2 };
        for (int i = 0; i < test.length - 1; i++) {
            for (int j = 0; j < test.length - i - 1; j++) {
                if (test[j] > test[j + 1]) {
                    int temp = test[j];
                    test[j] = test[j + 1];
                    test[j + 1] = temp;
                }
            }
        }
        for (int k = 0; k < test.length; k++) {
            System.out.println(test[k]);
        }

    }

}
  • 选择排序:在第一趟遍历N个数据,找出其中最小的数值与第一个元素交换,第二趟遍历剩下的N-1个数据,找出其中最小的数值与第二个元素交换……第N-1趟遍历剩下的2个数据,找出其中最小的数值与第N-1个元素交换,至此选择排序完成。
public class selectSort {

    public static void main(String[] args) {
        int[] test = { 6, 3, 5, 7, 0, 4, 1, 2 };
        for (int i = 0; i < test.length; i++) {
            int min = i;
            for (int j = i + 1; j < test.length; j++) {
                if (test[min] > test[j]) {
                    min = j;
                }
            }
            if (min != i) {
                int temp = test[i];
                test[i] = test[min];
                test[min] = temp;
            }
        }
        for (int k = 0; k < test.length; k++) {
            System.out.println(test[k]);
        }
    }

}
  • 插入排序:对于未排序数据,在已排序序列中从后向前扫描,找到相应的位置并插入。
public class insertSort {
    public static void main(String[] args) {
        int[] test = { 6, 3, 5, 7, 0, 4, 1, 2 };
        for (int i = 0; i < test.length; i++) {
            for (int j = i; j > 0; j--) {
                if (test[j] < test[j - 1]) {
                    int temp = test[j];
                    test[j] = test[j - 1];
                    test[j - 1] = temp;
                } else {
       
  • 15
    点赞
  • 233
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值