交换选择排序

问题描述 投票:0回答:1

接下来是选择排序的代码,当我尝试将最小元素与较大的元素交换时,它不能使用XOR运算符。它显示0代替值。但是交换正在处理两个常量整数。为什么?

import java.io.*;

class selection {

    public static void main(String s[])throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter n");
        int n=Integer.parseInt(br.readLine());
        System.out.println("Enter array");
        int a[]=new int[n];
        for(int i=0;i<n;++i) {
            a[i]=Integer.parseInt(br.readLine());
        }

        int min;
        System.out.println("Entered Array : ");
        for(int i=0;i<n;++i)
            System.out.print(a[i]+" ");

        for(int i=0;i<n;++i) {
            min=i;
            for(int j=i+1;j<n;++j) {
                if(a[min]>a[j])
                    min=j;
            }
            a[min]=a[min]^a[i];
            a[i]=a[min]^a[i];
            a[min]=a[min]^a[i];

        }

        System.out.println("\nSorted Array : ");
        for(int i=0;i<n;++i) {
            System.out.print(a[i]+" ");
        }
    }
}

输出是:

Enter n
8
Enter array
1
5
4
6
2
8
9
7
Entered Array : 
1 5 4 6 2 8 9 7 
Sorted Array : 
0 2 0 5 0 7 8 0 
java sorting selection swap xor
1个回答
3
投票

如果元素相等,则使用XOR交换元素将无法工作,并且在大多数书籍中都明确指出了这一点。这里发生的是以下内容 - 如果第i个元素是第i个迭代的最小元素,您将尝试将其与自身交换,从而使其值变为0。

为了避免这个问题,在使用XOR交换数字之前检查它们的值是否相等。在您的情况下,如果您确定数组不包含相等的元素,则只需在min==i时不交换。

© www.soinside.com 2019 - 2024. All rights reserved.