Antoniohawk

05-27-2004, 02:51 AM

How would I declare the variable numbers as global? I want to be able to access the same variable from any method so that the value of the variable is the same.

import TerminalIO.KeyboardReader;

public class SortAndDestroy{

public static void main (String[] args){

int[] numbers = {42,37,5,33,6};

KeyboardReader reader = new KeyboardReader();

int choice;

for(int i = 0; i < Names.numbers.length; i++){

System.out.print(numbers[i] + " ");

}

choice = reader.readInt("\nSelection[1] or Bubble[2] Sort? ");

if (choice == 1)

selectionSort(numbers);

else if (choice == 2)

bubbleSort(numbers);

else

System.out.println("That is not a choice.");

}

public static void selectionSort(int[] numbers){

for(int i = 0; i < numbers.length; i++){

int minIndex = findMinimum(numbers, i);

if(minIndex != 1)

swap(numbers, i, minIndex);

System.out.print(numbers[i] + " ");

}

}

public static int findMinimum(int[] numbers, int first){

int minIndex = first;

for(int i = first + 1; i < numbers.length; i++)

if(numbers[i] < numbers[minIndex])

minIndex = i;

return minIndex;

}

public static void swap(int[] numbers, int x, int y){

int temp = numbers[x];

numbers[x] = numbers[y];

numbers[y] = temp;

}

public static void bubbleSort(int[] numbers){

int k = 0;

boolean exchangeMade = true;

while((k < numbers.length - 1) && exchangeMade){

exchangeMade = false;

k++;

for(int j = 0; j < numbers.length - k; j++)

if(numbers[j] > numbers[j + 1]){

swap(numbers,j,j + 1);

exchangeMade = true;

}

}

}

}

import TerminalIO.KeyboardReader;

public class SortAndDestroy{

public static void main (String[] args){

int[] numbers = {42,37,5,33,6};

KeyboardReader reader = new KeyboardReader();

int choice;

for(int i = 0; i < Names.numbers.length; i++){

System.out.print(numbers[i] + " ");

}

choice = reader.readInt("\nSelection[1] or Bubble[2] Sort? ");

if (choice == 1)

selectionSort(numbers);

else if (choice == 2)

bubbleSort(numbers);

else

System.out.println("That is not a choice.");

}

public static void selectionSort(int[] numbers){

for(int i = 0; i < numbers.length; i++){

int minIndex = findMinimum(numbers, i);

if(minIndex != 1)

swap(numbers, i, minIndex);

System.out.print(numbers[i] + " ");

}

}

public static int findMinimum(int[] numbers, int first){

int minIndex = first;

for(int i = first + 1; i < numbers.length; i++)

if(numbers[i] < numbers[minIndex])

minIndex = i;

return minIndex;

}

public static void swap(int[] numbers, int x, int y){

int temp = numbers[x];

numbers[x] = numbers[y];

numbers[y] = temp;

}

public static void bubbleSort(int[] numbers){

int k = 0;

boolean exchangeMade = true;

while((k < numbers.length - 1) && exchangeMade){

exchangeMade = false;

k++;

for(int j = 0; j < numbers.length - k; j++)

if(numbers[j] > numbers[j + 1]){

swap(numbers,j,j + 1);

exchangeMade = true;

}

}

}

}