Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

public void sort(String [] [] names, int flag) where String [][] names is a Nx2

ID: 3594462 • Letter: P

Question

public void sort(String [] [] names, int flag)

where String [][] names is a Nx2 two dimensional array with each row has two elements representing

first name and last name.

This method sorts names based on first name or last name which is specified with the flag value, if the

flag equals 1, it sorts based on first name, for all other values, it sorts according to last names.

A data file is provided for testing. The first line is a number N followed by N lines with each line represents

a name of person.

How to run sample:

type *data.txt 1 or *data.txt 2 in the Cmd argument list

given

data.txt

11
Cordell Beasley
Jaylen Day
Sadie Benitez
Kadence Wiley
Lamar Scott
Jaslyn Gamble
Brooke Mendez
Leah Ryan
Maryjane Williamson

Explanation / Answer

I've implemented the code as per your requirement and added comments for better understandment.

Code:

------------------

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class SelectionSort {

private static String flag = ""; //flag for sorting condition

public static void main(String[] args) {

try {

String content = "";

String path = new File("").getAbsolutePath(); //Taking the path

BufferedReader bufferedReader = new BufferedReader(new FileReader(path+"/src/"+args[0])); //Opeinig the file

StringBuffer stringBuffer = new StringBuffer();

String line;

flag = args[1];

int count = 0;

//Reading file

while ((line = bufferedReader.readLine()) != null) {

if(count==0){

count++;

continue;

}

stringBuffer.append(line);

stringBuffer.append(" ");

}

bufferedReader.close();

content = stringBuffer.toString();

//Here the content is stored in string format in buffer,

//so I'm splitting the the buffer by new line character to the list of names

selectionSort(content.split(" ")); //Calling the sort function

} catch (IOException e) {

e.printStackTrace();

}

}

//sorting function

public static void selectionSort(String[] a) {

String [] arr1 = {};

String [] arr2 = {};

for (int i=0; i<a.length-1; i++) {

for (int j=i+1; j<a.length; j++) {

//Splitting the names into two parts

arr1 = a[i].split(" ");

arr2 = a[j].split(" ");

//Condition to sort by first name

if(flag.equals("1")){

//Comparing and shuffling

if (arr1[0].compareTo(arr2[0]) > 0) {

String temp=a[j]; a[j]=a[i]; a[i]=temp;

}

}

//Condition to sort by second name

else{

//Comparing and shuffling

if (arr1[1].compareTo(arr2[1]) > 0) {

String temp=a[j]; a[j]=a[i]; a[i]=temp;

}

}

}

}

//Printing the result

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

System.out.println(a[i]);

}

}

}