Computer Science, asked by neelndesai, 8 months ago

Write a program to input 50 names along with their weights in an array and sort the names in alphabetical order using selection sort technique. in java only

Answers

Answered by Anonymous
1

Answer:

public class SelectionSortTest

{

public static void main(String[] args)

{

String[] stringArray = {"Flash", "Green Arrow", "superman", "spiderman", "green lantern"};

System.out.println("Unsorted array:");

for(String element: stringArray)

System.out.print(element + " ");

System.out.println();

selectionSort(stringArray);

System.out.println("Sorted array:");

for(String element: stringArray)

System.out.print(element + " ");

System.out.println();

}

static void selectionSort(Comparable[] array)

{

int smallindex;

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

{

smallindex = i; // set first element as smallest

for(int j = i + 1; j < array.length; j++) // find smallest

if(array[j].compareTo(array[smallindex]) < 0)

smallindex = j;

if(smallindex != i)

swap(array, smallindex, i);

}

}

static void swap(Object[] array, int index1, int index2)

{

Object temp = array[index1];

array[index1] = array[index2];

array[index2] = temp;

}

}

But i want to change this so that the user has to input those names instead. Such that the outprint keeps asks "Enter the names" and you put whatever amount of names you want (separated by commas) then does the above task.

i Have tried replacing

String[] stringArray = {"Flash", "Green Arrow", "superman", "spiderman", "green lantern"};

with:

Scanner input = new Scanner(System.in);

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

{

System.out.print("Enter names " + (i + 1) + ": ");

array[i] = input.next():

Bu

How to Sort a String in Java alphabetically in Java?

Get the required string.

Convert the given string to a character array using the toCharArray() method.

Sort the obtained array using the sort() method of the Arrays class.

Convert the sorted array to String by passing it to the constructor of the String array.

Answered by harnathyadav2907
0

Explanation:

// Java program for implementation of Selection Sort

class SelectionSort

{

void sort(int arr[])

{

int n = arr.length;

// One by one move boundary of unsorted subarray

for (int i = 0; i < n-1; i++)

{

// Find the minimum element in unsorted array

int min_idx = i;

for (int j = i+1; j < n; j++)

if (arr[j] < arr[min_idx])

min_idx = j;

// Swap the found minimum element with the first

// element

int temp = arr[min_idx];

arr[min_idx] = arr[i];

arr[i] = temp;

}

}

Similar questions