排序数组所需的最小交换次数

时间:2014-11-09 20:32:18

标签: sorting

我有一个大小为n的数组,它包含从1到n的元素,按随机顺序排列。我可以交换任意两个元素,无论多少次。如何找到这样的交换的最小数量以使数组排序??

6 个答案:

答案 0 :(得分:0)

这可以在O(n)中完成。假设元素在1到n的范围内,并且没有重复。

noofswaps = 0
for i in range(len(A)):
    while A[i] != i + 1:
        temp = A[i]
        A[i] = A[A[i] - 1]
        A[temp - 1] = temp
        noofswaps += 1
print noofswaps

答案 1 :(得分:0)

static int minimumSwaps(int[] arr) {
        int swap=0;
        boolean newarr[]=new boolean[arr.length];

        for(int i=0;i<arr.length;i++){
            int j=i,count=0;

            while(!newarr[j]){
                newarr[j]=true;
                j=arr[j]-1;
                count++;
            }

            if(count!=0)
                swap+=count-1;
        }
        return swap;
}

答案 2 :(得分:0)

  

我将尝试使用javascript回答此问题。   这是到目前为止我尝试过的最佳代码:

 CREATE TABLE [dbo].[ClientDepartmentContact](
    [ClientDepartmentContactId] [int] IDENTITY(1,1) NOT NULL,
    [ClientId] [int] NOT NULL,
    [DepartmentId] [smallint] NOT NULL,
    [DispatchContactId] [int] NOT NULL,
    [DispatchType] [char](1) NOT NULL,
    [DispatchContactType] [char](1) NOT NULL,
 CONSTRAINT [PK_ClientDepartmentContact] PRIMARY KEY CLUSTERED 
(
    [ClientDepartmentContactId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_ClientDepartmentContact] UNIQUE NONCLUSTERED 
(
    [ClientId] ASC,
    [DepartmentId] ASC,
    [DispatchContactId] ASC,
    [DispatchType] ASC,
    [DispatchContactType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

--Index
ALTER TABLE [dbo].[ClientDepartmentContact] ADD  CONSTRAINT [PK_ClientDepartmentContact] PRIMARY KEY CLUSTERED 
(
    [ClientDepartmentContactId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

ALTER TABLE [dbo].[ClientDepartmentContact] ADD  CONSTRAINT [UK_ClientDepartmentContact] UNIQUE NONCLUSTERED 
(
    [ClientId] ASC,
    [DepartmentId] ASC,
    [DispatchContactId] ASC,
    [DispatchType] ASC,
    [DispatchContactType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO



CREATE TABLE [dbo].[ClientDepartmentContact](
    [ClientDepartmentContactId] [int] IDENTITY(1,1) NOT NULL,
    [ClientId] [int] NOT NULL,
    [DepartmentId] [smallint] NOT NULL,
    [DispatchContactId] [int] NOT NULL,
    [DispatchType] [char](1) NOT NULL,
    [DispatchContactType] [char](1) NOT NULL,
 CONSTRAINT [PK_ClientDepartmentContact] PRIMARY KEY CLUSTERED 
(
    [ClientDepartmentContactId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [UK_ClientDepartmentContact] UNIQUE NONCLUSTERED 
(
    [ClientId] ASC,
    [DepartmentId] ASC,
    [DispatchContactId] ASC,
    [DispatchType] ASC,
    [DispatchContactType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

--Index
ALTER TABLE [dbo].[ClientDepartmentContact] ADD  CONSTRAINT [PK_ClientDepartmentContact] PRIMARY KEY CLUSTERED 
(
    [ClientDepartmentContactId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

ALTER TABLE [dbo].[ClientDepartmentContact] ADD  CONSTRAINT [UK_ClientDepartmentContact] UNIQUE NONCLUSTERED 
(
    [ClientId] ASC,
    [DepartmentId] ASC,
    [DispatchContactId] ASC,
    [DispatchType] ASC,
    [DispatchContactType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO


CREATE TABLE [dbo].[DispatchContact](
    [DispatchContactId] [int] IDENTITY(1,1) NOT NULL,
    [Email] [varchar](254) NOT NULL,
 CONSTRAINT [PK_DispatchContact] PRIMARY KEY CLUSTERED 
(
    [DispatchContactId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_ContactAddress_Email] ON [dbo].[DispatchContact]
(
    [Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

ALTER TABLE [dbo].[DispatchContact] ADD  CONSTRAINT [PK_DispatchContact] PRIMARY KEY CLUSTERED 
(
    [DispatchContactId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
  

reference -1

     

reference -2

答案 3 :(得分:0)

使用哈希图进行最少交换2的Hackerrank Python代码

length = int(input())
arr= list(map(int,input().split()))
hashmap = {}

for i in range(0,len(arr)):
    hashmap[i+1] = [arr[i],False]

swap_count = 0
for e_pos, e_val in hashmap.items():
    if e_val[1] == False:
        e_val[1] = True
        if e_pos == e_val[0]:
            continue
        else:
            c = e_val[0]
            while hashmap[c][1] == False:
                hashmap[c][1] = True
                b = hashmap[c][0]
                c = b
                swap_count+=1
print(swap_count)

答案 4 :(得分:0)

GeeksForGeeks中有一个有趣的地方

  • 时间复杂度:O(N),其中N是数组的大小。
  • 辅助空间:O(1)

使用的方法是

  1. 对于arr []中的每个索引,请检查当前元素是否在正确的位置。由于数组包含从1到N的不同元素,因此我们可以简单地比较该元素与其在数组中的索引,以检查它是否在正确的位置。
  2. 如果当前元素不在正确的位置,则将其与占据其位置的元素交换(使用temp变量)
  3. 否则检查下一个索引(i + = 1)

这是代码

def minimumSwaps(arr):
    min_num_swaps = 0; 
    i = 0; 
    while (i < len(arr)):  
        if (arr[i] != i + 1): 
            while (arr[i] != i + 1): 
                temp = 0; 
                temp = arr[arr[i] - 1]; 
                arr[arr[i] - 1] = arr[i]; 
                arr[i] = temp; 
                min_num_swaps += 1; 

        i += 1; 
      
    return min_num_swaps;

可以轻松更新为

  • 删除分号

  • 消除对温度的需求

  • 用给定的整数输入n(以数组的大小)替换len(arr)

    def minimumSwaps(arr):
        min_num_swaps = 0
        i = 0
        while (i < n-1):  
            if (arr[i] != i + 1): 
                while (arr[i] != i + 1): 
                    arr[arr[i] - 1], arr[i] = arr[i], arr[arr[i] - 1]
                    min_num_swaps += 1
    
            i += 1; 
    
         return min_num_swaps
    

他们都将通过HackerRank中的所有15个测试用例

It works

答案 5 :(得分:-2)

您似乎在谈论bubble sort。在最坏的情况下,您会进行O(n^2)交换。