suyeonme

[Algorithm] 배열 reverse 하기 본문

프로그래밍👩🏻‍💻/알고리즘

[Algorithm] 배열 reverse 하기

suyeonme 2022. 6. 12. 18:07

해결 1)

public int[] reverseArr(int[] arr) {
  for(int i = 0; i < arr.length /2; i++) {
    int temp = arr[i];
    arr[i] = arr[arr.length - i -1];
    arr[arr.length - i -1] = temp;
   }
  return arr;
}

해결 2)

public void reverseArr2(int[] arr) {
  for(int i = 0; i < arr.length / 2; i++) {
    swap(arr, i, arr.length - i -1);
  }
}

public void swap(int[] arr, int idx1, int idx2) {
  int temp = arr[idx1];
  arr[idx1] = arr[idx2];
  arr[idx2] = temp;
}

 

 

Comments