简体   繁体   English

将整数数组的前半部分和奇数移动到后半部分

[英]move all even numbers on the first half and odd numbers to the second half in an integer array

I had an interview question which i could not solve. 我有一个面试问题,我无法解决。

Write method (not a program) in Java Programming Language that will move all even numbers on the first half and odd numbers to the second half in an integer array. Java编程语言中的Write方法(不是程序),它将整数数组的前半部分和奇数移动到后半部分。

Eg Input = {3,8,12,5,9,21,6,10}; 例如输入= {3,8,12,5,9,21,6,10}; Output = {12,8,6,10,3,5,9,21}. 输出= {12,8,6,10,3,5,9,21}。

The method should take integer array as parameter and move items in the same array (do not create another array). 该方法应将整数数组作为参数,并在同一数组中移动项目(不要创建另一个数组)。 The numbers may be in different order than original array. 这些数字可能与原始数组的顺序不同。 This is algorithm test, so try to give as efficient algorithm as you can (possibly linear O(n) algorithm). 这是算法测试,因此请尝试提供尽可能有效的算法(可能是线性O(n)算法)。 Avoid using built in functions/API. 避免使用内置函数/ API。 * *

Also some basic intro to what is data structure efficiency 还介绍了什么是数据结构效率的基本介绍

Keep two indices: one to the first odd number and one to the last even number. 保留两个索引:一个到第一个奇数,一个到最后一个偶数。 Swap such numbers and update indices. 交换这些数字并更新索引。

(With a lot of help from @manu-fatto's suggestion) I believe this would do it: (在@ manu-fatto的建议中有很多帮助)我相信这可以做到:

private static int[] OddSort(int[] items)
{
    int oddPos, nextEvenPos;
    for (nextEvenPos = 0; 
         nextEvenPos < items.Length && items[nextEvenPos] % 2 == 0;
         nextEvenPos++) { }
    // nextEvenPos is now positioned at the first odd number in the array, 
    // i.e. it is the next place an even number will be placed

    // We already know that items[nextEvenPos] is odd (from the condition of the 
    // first loop), so we'll start looking for even numbers at nextEvenPos + 1
    for (oddPos = nextEvenPos + 1; oddPos < items.Length; oddPos++)
    {
        // If we find an even number
        if (items[oddPos] % 2 == 0)
        {
            // Swap the values
            int temp = items[nextEvenPos];
            items[nextEvenPos] = items[oddPos];
            items[oddPos] = temp;
            // And increment the location for the next even number
            nextEvenPos++;
        }
    }

    return items;
}

This algorithm traverses the list exactly 1 time (inspects each element exactly once), so the efficiency is O(n). 该算法正好遍历列表1次(对每个元素正好检查一次),因此效率为O(n)。

// to do this in one for loop //在一个for循环中执行此操作

public static void evenodd(int[] integer) {

    int i = 0, temp = 0;
    int j = integer.length - 1;

    while (j >= i) {
        // swap if found odd even combo at i and j
        if (integer[i] % 2 != 0 && integer[j] % 2 == 0) {
            temp = integer[i];
            integer[i] = integer[j];
            integer[j] = temp;
            i++;
            j--;

        } else {
            if (integer[i] % 2 == 0) {
                i++;
            }
            if (integer[j] % 2 == 1) {
                j--;
            }

        }

    }
} 

@JLRishe, @JLRishe,

Your algorithm doesn't maintain the order. 您的算法无法维持顺序。 For a simple example, say {1,5,2}, you will change the array to {2,5,1}. 举一个简单的例子,说{1,5,2},您将把数组更改为{2,5,1}。 I could not comment below your post as I am a new user and lack reputations. 由于我是新用户并且缺乏声誉,因此我无法在您的信息下方发表评论。

public static void sorted(int [] integer) {

int i, j , temp;

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

     if (integer[i] % 2 == 0) {
         for (j = i;  j < integer.length;  j++) {
              if (integer[j] % 2 == 1) {
                  temp = y[i];
                  y[i] = y[j];
                  y[j] = temp;
              }
          }
      }
      System.out.println(integer[i]);
}

public static void main(String args[]) {

       sorted(new int[]{1, 2,7, 9, 4}); 



}

}

The answer is 1, 7, 9, 2, 4. 答案是1、7、9、2、4。

Could it be that you were asked to implement a very basic version of the BubbleSort where the sort value of element e, where e = arr[i], = e%2==1 ? 可能是您被要求实现一个非常基本的BubbleSort版本,其中元素e的排序值为e = arr [i],= e%2 == 1吗? 1 : -1 ? 1:-1? Regards Leon 问候莱昂

class Demo
{
public void sortArray(int[] a)
{
int len=a.length;
int j=len-1;
for(int i=0;i<len/2+1;i++)
{
if(a[i]%2!=0)
{
while(a[j]%2!=0 && j>(len/2)-1)
j--;
if(j<=(len/2)-1)
break;
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
for(int i=0;i<len;i++)
System.out.println(a[i]);
}

public static void main(String s[])
{
int a[]=new int[10];
System.out.println("Enter 10 numbers");
java.util.Scanner sc=new java.util.Scanner(System.in);
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
new Demo().sortArray(a);
}
}
private static void rearrange(int[] a) {
    int i,j,temp;
    for(i = 0, j = a.length - 1; i < j ;i++,j--) {
        while(a[i]%2 == 0 && i != a.length - 1) {
            i++;
        }
        while(a[j]%2 == 1 && j != 0) {
            j--;
        }
        if(i>j)
            break;
        else {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }       
}
public void sortEvenOddIntegerArray(int[] intArray){
    boolean loopRequired = false;
    do{
        loopRequired = false;
        for(int i = 0;i<intArray.length-1;i++){

            if(intArray[i] % 2 != 0 && intArray[i+1] % 2 == 0){

                int temp = intArray[i];
                intArray[i] = intArray[i+1];
                intArray[i+1] = temp;
                loopRequired = true;
            }
        }
    }while(loopRequired);
}

You can do this with a single loop by moving odd items to the end of the array when you find them. 您可以通过找到奇数项将它们移到数组的末尾来进行单循环。

static void EvensToLeft(int[] items) {
    int end = items.length;
    for (int i = 0; i < end; i++) {
        if (items[i] % 2) {
            int t = items[i];
            items[i--] = items[--end];
            items[end] = t;
        }
    }
}

Given an input array of length n the inner loop executes exactly n times, and computes the parity of each array element exactly once. 给定一个长度为n的输入数组,内部循环将精确执行n次,并计算每个数组元素的奇偶校验一次。

Use two counters i=0 and j=a.length-1 and keep swapping even and odd elements that are in the wrong place. 使用两个计数器i = 0和j = a.length-1,并继续交换错误位置的偶数和奇数元素。

  public int[] evenOddSort(int[] a) {
        int i = 0;
        int j = a.length - 1;
        int temp;
        while (i < j) {
            if (a[i] % 2 == 0) {
                i++;
            } else if (a[j] % 2 != 0) {
                j--;
            } else {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
                i++;
                j--;
            }
        }
        return a;
    }

public class SeperatOddAndEvenInList { 公共类SeperatOddAndEvenInList {

public static int[] seperatOddAndEvnNos(int[] listOfNumbers) {
    int oddNumPointer = 0;
    int evenNumPointer = listOfNumbers.length - 1;
    while(oddNumPointer <= evenNumPointer) {                
            if(listOfNumbers[oddNumPointer] % 2 == 0) { //even number, swap to front of last known even number
                int temp;
                temp = listOfNumbers[oddNumPointer];
                listOfNumbers[oddNumPointer] = listOfNumbers[evenNumPointer];
                listOfNumbers[evenNumPointer] = temp;
                evenNumPointer--;
            }
            else {  //odd number, go ahead... capture next element
                oddNumPointer++;
            }


    }
    return listOfNumbers;
}


public static void main(String[] args) {
    // TODO Auto-generated method stub
    int []arr = {3, 8, 12, 5, 9, 21, 6, 10};
    int[] seperatedArray = seperatOddAndEvnNos(arr);
    for (int i : seperatedArray) {
        System.out.println(i);
    }

}

} }

efficiency is O(log n). 效率为O(log n)。

public class TestProg {
public static void main(String[] args) {
    int[] input = { 32, 54, 35, 18, 23, 17, 2 };
    int front = 0;
    int mid = input.length - 1;
    for (int start = 0; start < input.length; start++) {
    //if current element is odd
        if (start < mid && input[start] % 2 == 1) {
    //swapping element is also odd?
            if (input[mid] % 2 == 1) {
                mid--;
                start--;
            } 
    //swapping element is not odd then swap
     else {
                int tmp = input[mid];
                input[mid] = input[start];
                input[start] = tmp;
                mid--;
            }
        }

    }
    for (int x : input)
        System.out.print(x + " ");
}

} }

public class ArraysSortEvensFirst { 公共类ArraysSortEvensFirst {

public static void main(String[] args) {
    int[] arr = generateTestData();
    System.out.println(Arrays.toString(arr));

    ArraysSortEvensFirst test = new ArraysSortEvensFirst();
    test.sortEvensFirst(arr);

}

private static int[] generateTestData() {
    int[] arr = {1,3,5,6,9,2,4,5,7};
    return arr;
}

public int[] sortEvensFirst(int[] arr) {
    int end = arr.length;

    int last = arr.length-1;
    for(int i=0; i < arr.length; i++) {
        // find odd elements, then move to even slots
        if(arr[i]%2 > 0) {
            int k = findEven(last, arr);
            if(k > i) swap(arr, i, k);
            last = k;
        }
    }

    System.out.println(Arrays.toString(arr));
    return arr;
}

public int findEven(int last, int[] arr) {
    for(int k = last; k > 0; k--) {
        if(arr[k]%2 == 0) {
            return k;
        }
    }
    return -1; // not found;
}

public void swap(int[] arr, int x, int y) {
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
}

} }

Output: [1, 3, 5, 6, 9, 2, 4, 5, 7] [4, 2, 6, 5, 9, 3, 1, 5, 7] 输出:[1、3、5、6、9、2、4、5、7] [4、2、6、5、9、3、1、5、7]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM