2014-02-13 2 views
0

내 프로그램에서 요소가 어디에 속해야 하는지를 찾는 데 이진 검색을 사용하여 올바른 위치에 배치하고 요소를 한 칸 오른쪽으로 이동하여 배열을 정렬합니다. 내 바이너리와 관련된 부분을 찾을 수 있지만 올바른 위치에 배치하고 다른 요소를 이동하는 데 문제가 있습니다. 요소는 한 번에 하나씩 (순서대로 삽입) 텍스트 파일에서 읽혀 이상적으로 다음과 같이 작동합니다. 17 come -> [17, ..], 65 comes -> [17,65, ..], 20은 ~> [17,20,65, ..] 등입니다. 제 출력물은 완전히 잘못되었습니다. 내 코드와 출력은 다음과 같습니다. 41 55 48 34 84 78 89 94 61 108 74 76 97 62 121 119 132 110 144 156 160 146 164 170 75 이것은 완전히 고장난 것입니다 : (배열에서 문제가되는 배열 요소 배열

여기 내 코드 :

여기
static void insertInOrder(int[] arr, int cnt, int newVal) 
{ 
    //arr is assumed to be big enough for values + it's an empty array 
    int binaryIndex = bSearch(arr,cnt,newVal); //returns a negative value if not duplicate 
    int positiveIndex = (-(binaryIndex))-1; //transforms binaryIndex into a positive value of the correct index where number belongs 
    for (int i = arr.length-1;i>=positiveIndex;i--){ 
     if (i<=0)break; 
      arr[i]=arr[i-1]; 
    } 
    arr[positiveIndex]=newVal; 
} 

내 bSearch입니다 :

귀하의 for -loop 그렇지 않으면 당신은 당신의 새로운 요소가 배치되는 경우 목표 위치로 목표 위치의 왼쪽 한 장소 인 요소를 이동, i>binaryIndex에서 휴식하는
public static int bSearch(int[] a, int cnt, int key) 
{ 
    int high = cnt-1; 
    int low = 0; 
    int mid = (high+low)/2; 

    while (low <= high) { 

     if (key==a[mid]){ 
      return mid; 
     } 
     else if (key < a[mid]){ 
      high = mid-1; 
      mid = (high+low)/2; 
     } 
     else { 
      low = mid +1; 
      mid = (high+low)/2; 
     } 

    } 
    return -(mid+1); 

} 
+0

는 어렵다 bSearch를 구현하지 않으면 무엇이 잘못 될지 알려주십시오. 다른 코드는 상당히 합리적으로 보입니다. – gregkow

+3

'bSearch' 란 무엇입니까? 특히 가치가 없다면 무엇을 반환합니까? –

+0

bSearch는 요소를 배열에 배치해야하는 위치를 반환하는 메서드입니다. 기본적으로 수정 된 이진 검색입니다. – ComicStix

답변

0

대신 반환을 - (중간 + 1), I 반환 할 필요 - (낮은 + 1)

0

그 후.

+0

break 문을 변경 한 후이 결과를 얻었습니다 : 94 121 144 0 146 78 119 160 164 170 0 0 74 84 0 0 0 48 55 76 97 0 0 :/ – ComicStix

+0

'positiveIndex'는'binaryIndex'에 의한 것입니다. 그리고 그것은 오타입니다? 그리고'bSearch' 알고리즘을 추가로 확인하십시오. – Smutje

0

정확한 출력을 얻으려면 일부 코드를 수정했습니다. 아래의 코드를 찾아주세요 : -

public class StackOverflow { 
public static void main(String args[]) { 
    int[] intArray = new int[10]; 
    // Just to try the case I am passing the hard-coded value 
    insertInOrder(intArray,lengthArray(intArray),50); 
    insertInOrder(intArray,lengthArray(intArray),60); 
    insertInOrder(intArray,lengthArray(intArray),55); 
    insertInOrder(intArray,lengthArray(intArray),50); 
    //Displaying the sorted array output 
    for(int intA : intArray) { 
     System.out.println("Sorted intResultArray" + intA); 
    } 
} 
// To return the exact count of element in array. I hope you are not inserting 0 as a value because I have use default value. The reason to do it is that default length property of ARRAY will return the actual size of array 
// to get the exact count of element 
public static int lengthArray(int[] intArrLen) { 
    int count = 0; 
    for (int i = 0;i < intArrLen.length - 1;i++) { 
     if(intArrLen[i] != 0) { 
      count++; 
     } 
    } 
    return count; 
} 
public static void insertInOrder(int[] arr, int count, int newVal) // Here 'count' refers to exact count of element in array 
{ 
    int binaryIndex = bSearch(arr,count,newVal); 
    if (arr[arr.length - 1] == 0) {  // I have added to ensure that there is enough space to move element further down the array 
     for (int i = lengthArray(arr);i > binaryIndex;i--) { 
      arr[i]=arr[i-1]; 
     } 
    } else { 
     System.out.println("There is no space to move element in array"); 
    } 
    arr[binaryIndex]=newVal; 
} 
public static int bSearch(int[] a, int cnt, int key) { 
    int high = cnt-1; 
    int low = 0; 
    int mid = 0; 
    if(high == -1) { 
     return low; 
    } else { 
     mid = (high+low)/2; 
    } 
    while (low <= high) { 
     if (key==a[mid]){ 
      return (mid + 1); // I am returning 'mid + 1' in case if number already exist 
     } 
     else if (key < a[mid]){ 
      high = mid-1; 
      mid = (high+low)/2; 
     } 
     else { 
      low = mid +1; 
      mid = (high+low)/2; 
     } 
    } 
    return (mid+1); 
    } 
} 

출력 : -

Sorted intResultArray50 
Sorted intResultArray50 
Sorted intResultArray55 
Sorted intResultArray60 
Sorted intResultArray0 
Sorted intResultArray0 
Sorted intResultArray0 
Sorted intResultArray0 
Sorted intResultArray0 
Sorted intResultArray0 
+0

코드를 보내 주셔서 감사합니다! 그러나 나는 내 문제를 해결했다. 내 bSearch에서 중간 대신 낮은 것을 사용하기로되어있었습니다. – ComicStix