小编bub*_*leQ的帖子

冒泡排序最坏的例子是O(n*n),怎么样?

我正在尝试冒泡排序.有5个元素,数组未排序.泡沫排序的最坏情况是O(n ^ 2).

作为我正在使用的例子

A = {5,4,3,2,1}

在这种情况下,比较应该是5 ^ 2 = 25.使用手动验证和代码,我得到比较计数为20.以下是冒泡排序实现代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SortingAlgo
{
class Program
{
    public static int[] bubbleSort(int[] A)
    {
        bool sorted = false;
        int temp;
        int count = 0;
        int j = 0;
            while (!sorted)
            {
                j++;
                sorted = true;
                for (int i = 0; i < (A.Length - 1); i++)
                {
                    count++;
                    if(A[i] > A[i+1])
                    {
                        temp = A[i];
                        A[i] = A[i+1];
                        A[i+1] = temp;
                        sorted …
Run Code Online (Sandbox Code Playgroud)

c# algorithm

9
推荐指数
5
解决办法
2万
查看次数

标签 统计

algorithm ×1

c# ×1