Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package student;
- import java.io.*;
- import java.util.*;
- import student.Song.CmpArtist;
- /*
- * SearchByArtistPrefix.java
- * starting code
- * Boothe 2016
- */
- public class SearchByArtistPrefix {
- private Song[] songs; // The constructor fetches and saves a reference to the song array here
- public SearchByArtistPrefix(SongCollection sc) {
- songs = sc.getAllSongs();
- }
- private ArrayList<Song> foundSongs = new ArrayList<Song>();
- ArrayList<Song> tempSongs = new ArrayList<Song>();
- /**
- * find all songs matching artist prefix
- * uses binary search
- * should operate in time log n + k (# matches)
- */
- public Song[] search(String artistPrefix) {
- // write this method
- Song tempSong = new Song(artistPrefix, "thisIsTitle", "thisIsLyrics");
- CmpArtist cmp = new CmpArtist();
- int returnValue = 0;
- while(){
- //this should return an int value either ; negative - if the element being searched for
- //is not found.. or a positive int representing at what element in the array the searched element is
- returnValue = Arrays.binarySearch(songs, tempSong, cmp);
- //if the item is not found
- if (returnValue < 0) {
- break;
- }
- //add the found song to foundSongs array
- foundSongs.add(songs[returnValue]);
- //remove the found song from original array, so not to re-copy
- songs[returnValue] = null;
- }
- //debug
- System.out.println("out of forever loop");
- songs = foundSongs.toArray(new Song[songs.length]);
- //preserve ordering
- Arrays.sort(songs);
- return songs;
- }
- public static void main(String[] args) {
- if (args.length == 0) {
- System.err.println("usage: prog songfile [search string]");
- return;
- }
- SongCollection sc = new SongCollection(args[0]);
- SearchByArtistPrefix sbap = new SearchByArtistPrefix(sc);
- if (args.length > 1){
- System.out.println("searching for: "+args[1]);
- Song[] byArtistResult = sbap.search(args[1]);
- // to do: show first 10 matches
- for (int i = 0; i <= 10; i++) {
- System.out.println("First 10 matches " + sbap.search("Be")[i].getArtist());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement