Keep track of the lowest numbers in an array

霸气de小男生 提交于 2019-12-02 14:31:31

Do 2 separate loops instead. One to find lowest number, second to collect indexes.

int minValue = 1000000; //
for(int i =0; i< player.length; i++){
  if(player[i] < minValue){
    minValue = player[i];
  }
}
int j =0;
for(int i =0; i< player.length; i++){
  if(player[i]==minValue){
    min[j]=i;
    j++;
  }
}

One way is to have a sorted array, but it might be an overhead as far as insertion into the array is concerned.

The other method is to encapsulate the array in a data structure which internally keeps track of the index of the lowest value in the array. This data structure will have special methods for insertion and deletion which would always check while inserting and deleting to update the private member if the new number to be inserted is lower than the current lowest number.

This data structure should also expose a method to return the index of the lowest number in the array, which is already stored in a member variable.

One way to sort lowest numbers in array

// let array be of size x
 int arr[]=new int[x];

// Now,assign some values to array

int smallest=arr[0]; // assign any value to smallest

// logic

  for( int i=0; i < arr.length; i++ ) {
     if( smallest > arr[i] ) {
       smallest = arr[i];
     }
   }

   System.out.println(smallest); // gets the smallest number out on output stream

Unless this is homework, you should just have an Object for each player and score. You can add them to a PriorityQueue to always get the lowest or add them to a Collection/array[] and call sort().

You may want to keep just one copy, but that makes more work for yourself and only saves the computer a milli-second at most.

Your time is worth more than the computers most of the time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!