import java.util.Arrays;
public class Array {
int[] a = { 5 , 8 , 7 , 3 , 9 , 1 , 11 , 21 , 6 , 4 };
public static void main(String[] args)
{
int[] a = {5,8,7,3,9,1,11,21,6,4};
int i;
for(i = 0; i<a. length; i )
a[i] = (int)(java.lang.Math.random() );
int smallest = 0, largest =0 ;
for(i =1; i<a.length; i ){
if(a[i] < a[smallest])
smallest = i;
if(a[i] > a[largest])
largest = i;
}
swap(0, smallest);
swap(a. length-1 ,largest);
for(i =0; i<a. length; i )
System.out.print(a[i] " ");
}
public static void swap(int i, int j){
}
}
CodePudding user response:
a[i] = (int)(java.lang.Math.random() ); this is setting all the elements in the array to 0 to start with.
CodePudding user response:
In order to swap two array elements you need their index, not their value.
A static method like main
cannot access normal fields of Array.
Best have
void orderSmallestAndLargest(int[] a) {
... all code here ...
}
public static void main(String[] args) {
int[] mya = ...
System.out.println("Before: " Arrays.toString(mya));
new Array().orderSmallestAndLargest(mya);
System.out.println("After: " Arrays.toString(mya));
}
The smallest value could be initialized to Integer.MAX_VALUE
, and the largest value to Integer.MIN_VALUE
. So they will be changed.
And as set besides the value you need the index.