How to rearrange data in array so that two similar items are not next to each other?

后端 未结 8 1892
暗喜
暗喜 2020-12-31 12:00

Just want to rearrange the data in array so that similar items are not next to each. The data should not be removed from the array, if it can\'t be rearranged it can be put

8条回答
  •  被撕碎了的回忆
    2020-12-31 12:12

    Java: Something like this?

    void resortArray(ArrayList arr) {
      for(int i = 0; i < arr.size(); i++) //loop trough array
        if(arr.get(i) == arr.get(i + 1)) { //if the next value is the same as current one
          for(int j = i+2; j < arr.size(); j++) { //loop again trough array from start point i+2
            if(arr.get(i+1) != arr.get(j)) { //swap values when you got a value that is different
              int temp = arr.get(i+1);
              arr.set(i+1, arr.get(j));
              arr.set(j, temp);
              break;
            }  
          }
        }
      }
    }
    

提交回复
热议问题