当前位置:   article > 正文

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

数据结构面试算法

第二章排序

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]);
        }

    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 选择排序:在第一趟遍历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]);
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 插入排序:对于未排序数据,在已排序序列中从后向前扫描,找到相应的位置并插入。
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 {
       
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/868790
推荐阅读
相关标签
  

闽ICP备14008679号