python时间复杂度到0(n)冒泡排序_排序算法(一)(时间复杂度均为O(n*n))

[1,2,3,5,2,3],6

[1,2,2,3,3,5]

冒泡排序:

package test;

public class BubbleSort {

public int[] bubbleSort(int[] A, int n) {

int temp;

for (int j = 0; j < n - 1; j++) {

for (int i = 0; i < n - 1 - j; i++) {

if (A[i + 1] < A[i]) {

temp = A[i];

A[i] = A[i + 1];

A[i + 1] = temp;

}

}

}

return A;

}

public static void main(String[] args) {

BubbleSort bubSort = new BubbleSort();

int[] A = { 1, 2, 3, 5, 2, 3 };

int[] ASort = bubSort.bubbleSort(A, A.length);

for (int i = 0; i < ASort.length; i++) {

System.out.println(ASort[i]);

}

}

}

运行结果如下:

1 2 2 3 3 5

时间复杂度为O(n*n);两两相互比较,较小的元素向上冒泡,较大的元素沉到水底。

选择排序:

package test;

public class SelectionSort {

public int[] selectionSort(int[] A, int n) {

// write code here

int temp;

for (int j=0;j

{

for (int i=j+1;i

{

if (A[j]>A[i])

{

temp=A[j];

A[j]=A[i];

A[i]=temp;

}

}

}

return A;

}

public static void main(String[] args) {

SelectionSort selSort = new SelectionSort();

int[] A = { 1, 2, 3, 5, 2, 3 };

int[] ASort = selSort.selectionSort(A, A.length);

for (int i = 0; i < ASort.length; i++) {

System.out.println(ASort[i]);

}

}

}

运行结果如下:

1 2 2 3 3 5

时间复杂度为O(n*n);第一位存储最小的元素,第二位存储第二小的元素,以此类推。

插入排序:

package test;

public class InsertionSort {

public int[] insertionSort(int[] A, int n) {

int temp;

for (int j = 1; j < n; j++) {

for (int i = j; i > 0; i--) {

if (A[i] < A[i - 1]) {

temp = A[i];

A[i] = A[i - 1];

A[i - 1] = temp;

}

}

}

return A;

}

public static void main(String[] args) {

InsertionSort insSort = new InsertionSort();

int[] A = { 1, 2, 3, 5, 2, 3 };

int[] ASort = insSort.insertionSort(A, A.length);

for (int i = 0; i < ASort.length; i++) {

System.out.println(ASort[i]);

}

}

}

运行结果如下: 1 2 2 3 3 5

时间复杂度为O(n*n),第二个数同第一个数比,如果比第一个小,就交换位置,然后第三个数同第二个数比,如果小就交换位置,并且继续同第一个数比较大小,如果小就交换位置,以此类推。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值