コード例 #1
0
    def test_sortFully(self):
        sortTest = SelectionSort(['abc', 1.0, 'ab', 'aa', 3, 1.2, 4, 'abb'])
        sortTest.sortFully()

        self.assertEqual(sortTest.unsorted, [])
        self.assertEqual(sortTest.sorted,
                         [1.0, 1.2, 3, 4, 'aa', 'ab', 'abb', 'abc'])
コード例 #2
0
    def test_sortNext(self):
        sortTest = SelectionSort(['a', 1.2, 4])
        sortTest.sortNextElement()
        sortTest.sortNextElement()

        self.assertEqual(sortTest.unsorted, ['a'])
        self.assertEqual(sortTest.sorted, [1.2, 4])
コード例 #3
0
class OrdinationTest(unittest.TestCase):
	
	def setUp(self):
		self.oddSize = [9,8,7,6,5,4,3,2,1,0]
		self.evenSize = [9,8,7,6,5,4,3,2,1]
		self.empty = []
		self.equal = [5,5,5,5,5,5]
		self.repeated = [5,9,8,7,6,8,6,8,5,4,3,2]
		self.ordered = [1,2,3,4,5,6,7,8,9]
		
                # Escolher o algoritmo a ser usado na suite de testes
		#self.algorithm = GnomeSort()
	        #self.algorithm = InsertionSort()
                self.algorithm = SelectionSort()

	def genericTest(self,array):
		copy = array[:]
		self.algorithm.sort(array)
		copy.sort()
		self.assertEqual(copy,array)

	def invalidParameters(self,array,leftIndex,rightIndex):
		copy = array[:]
		self.algorithm.sort(array,leftIndex,rightIndex)
		self.assertEqual(copy,array)

	def testOrdinationOdd(self):
		self.genericTest(self.oddSize)
	def testOrdinationEven(self):
		self.genericTest(self.evenSize)
	def testOrdinationEmpty(self):
		self.genericTest(self.empty)
	def testOrdinationEqual(self):
		self.genericTest(self.equal)
	def testOrdinationRepeated(self):
		self.genericTest(self.repeated)
	def testOrdinationOrdered(self):
		self.genericTest(self.ordered)

	def testInvalidLeftIndex(self):
		self.invalidParameters(self.oddSize,-5,3)
		self.invalidParameters(self.evenSize,-5,3)
		self.invalidParameters(self.empty,-5,3)
		self.invalidParameters(self.equal,-5,3)
		self.invalidParameters(self.repeated,-5,3)
		self.invalidParameters(self.ordered,-5,3)
	
	def testInvalidRightIndex(self):
		self.invalidParameters(self.oddSize,0,len(self.oddSize))
		self.invalidParameters(self.evenSize,0,len(self.evenSize))
		self.invalidParameters(self.empty,0,len(self.empty))
		self.invalidParameters(self.equal,0,len(self.equal))
		self.invalidParameters(self.repeated,0,len(self.repeated))
		self.invalidParameters(self.ordered,0,len(self.ordered))

	def testInvalidLeftRight(self):
		self.invalidParameters(self.oddSize,5,5)
		self.invalidParameters(self.evenSize,5,3)
コード例 #4
0
	def setUp(self):
		self.oddSize = [9,8,7,6,5,4,3,2,1,0]
		self.evenSize = [9,8,7,6,5,4,3,2,1]
		self.empty = []
		self.equal = [5,5,5,5,5,5]
		self.repeated = [5,9,8,7,6,8,6,8,5,4,3,2]
		self.ordered = [1,2,3,4,5,6,7,8,9]
		
                # Escolher o algoritmo a ser usado na suite de testes
		#self.algorithm = GnomeSort()
	        #self.algorithm = InsertionSort()
                self.algorithm = SelectionSort()
コード例 #5
0
ファイル: main.py プロジェクト: dcwalke3/Algortithms
def main():
    ConsoleClear()
    while (True):
        """ 'data' is a dictonary just cause I prefer a dictonary with mutliple arrays in it verses having to do nested arrays."""
        data = {}

        listNum = input("Enter the number of list to sort: ")
        """ Validating if everything is numeric."""
        while (listNum.isnumeric() == False):
            ConsoleClear()
            print("Please make sure your input is numeric.")
            listNum = input("Enter the number of list to sort: ")

        listSize = input("Enter the Size of the List: ")

        while (listNum.isnumeric() == False):
            ConsoleClear()
            print("Please make sure your input is numeric.")
            print("Enter the number of list to sort: " + listNum)
            listNum = input("Enter the number of list to sort: ")
        """ Creates a list for each list desired. Adds each to a dictonary."""
        for i in range(int(listNum)):
            tempArray = []
            for j in range(int(listSize)):
                tempArray.append(random.randint(1, 100))
            data[i] = tempArray

        print("Begin Sorting...\n")
        """ Timer activates than the algorithm will go through each key(array) in the dictonary and make a deepcopy of it for use. """
        with Timer(True):
            for key in data:
                dataCopy = copy.deepcopy(data[key])
                BubbleSort(dataCopy)
        print("Bubble Sort Complete\n\n")

        with Timer(True):
            for key in data:
                dataCopy = copy.deepcopy(data[key])
                SelectionSort(dataCopy)

        print("Selection Sort Complete\n\n")

        with Timer(True):
            for key in data:
                dataCopy = copy.deepcopy(data[key])
                InsertionSort(dataCopy)
        print("Insertion Sort Complete\n\n")

        option = input(
            "Enter 'Q' to quit or any other key to continue: ").upper()
コード例 #6
0
ファイル: Program.py プロジェクト: oclipa/sort-algorithms
    def run():

        # orig_obj_values = [ "apple", "orange", "banana", "apple", "coconut", "olive", "egg", "banana", "ham", "milk", "coconut", "cheese" ]

        value_count = 10000

        orig_obj_values = np.empty(shape=(value_count))

        min = value_count + 1
        max = -1
        for i in range(value_count):
            # in c#, random.next(incl, excl), but in python, randint(incl, incl)
            v = random.randint(0, value_count - 1)

            if v < min: min = v
            if v > max: max = v

            orig_obj_values[i] = int(v)

        obj_values = np.empty_like(orig_obj_values)
        obj_values[:] = orig_obj_values

        algorithms = np.array([
            BubbleSort(),
            SelectionSort(),
            InsertionSort(),
            QuickSort(),
            MergeSort(),
            CountingSort(min, max),
            HeapSort(),
            RadixSort()
        ])

        print("Python")
        print("STARTED --------------------------------------------")

        for algorithm in algorithms:

            # reset input values
            obj_values[:] = orig_obj_values

            algorithm.run(obj_values)

        print(" ")
        print("STOPPED --------------------------------------------")
コード例 #7
0
class TestSelectionSort(unittest.TestCase):
	def setUp(self):
		self.selectionSort = SelectionSort()

	def test_0(self):
		print("{} Can create SelectionSort object".format(inspect.stack()[0][3]))

	def test_1(self):
		print("{} When given list of unique positive numbers, can find lowest number".format(inspect.stack()[0][3]))
		numberList = [3,2,5]
		self.assertEqual(numberList[self.selectionSort.findIndexOfLowestInList(numberList)], 2)

	def test_2(self):
		print("{} When given list of unique numbers, can find lowest number".format(inspect.stack()[0][3]))
		numberList = [3,2,-5]
		self.assertEqual(numberList[self.selectionSort.findIndexOfLowestInList(numberList)], -5)

	def test_3(self):
		print("{} When given list of numbers, can find lowest number".format(inspect.stack()[0][3]))
		numberList = [3,2,2,5]
		self.assertEqual(numberList[self.selectionSort.findIndexOfLowestInList(numberList)], 2)

	def test_4(self):
		print("{} Swapping numbers in small list, where from > to".format(inspect.stack()[0][3]))
		numberList = [2,3,4]
		self.assertEqual(self.selectionSort.swapFromTo(numberList,2,0), [4,3,2])

	def test_5(self):
		print("{} Swapping numbers in small list, where from < to".format(inspect.stack()[0][3]))
		numberList = [2,3,4]
		self.assertEqual(self.selectionSort.swapFromTo(numberList,0,2), [4,3,2])

	def test_6(self):
		print("{} Can sort small list".format(inspect.stack()[0][3]))
		numberList = [2,3,5,6,4,7]
		self.assertEqual([2,3,4,5,6,7], self.selectionSort.sort(numberList))

	def test_7(self):
		print("{} Can sort HUGE list".format(inspect.stack()[0][3]))
		hugeList = self.generateHugeList(1000)
		sortedHugeList = self.selectionSort.sort(hugeList)
		for i,num in enumerate(sortedHugeList[:-1]):
			self.assertGreater(sortedHugeList[i+1], sortedHugeList[i])

	def generateHugeList(self,length):
		return random.sample(range(length*10), length)
コード例 #8
0
def Main(array_to_be_sorted):

    acceptedTypes = [int, float, str]

    assert (type(array_to_be_sorted) == list
            ), "The input must be in the form of a list."

    for item in array_to_be_sorted:
        assert (type(item)
                in acceptedTypes), "Type %s unaccepted." % str(type(item))

    assert array_to_be_sorted != [], "The array must not be empty."

    ##      The code above is run before anything else
    ##      to insure the input is formatted correctly.
    ##      Can be edited if the accepted format/types change.

    sortChoice = input("\nWhich sorting algorith would you like to use?\n\n" +
                       "1. Selection Sort\n" + "2. Insertion Sort\n\n" +
                       "Insert your choice: ")

    if sortChoice == "1":
        temp = SelectionSort(array_to_be_sorted)
        temp.sortFully()
        return temp.sorted
        del temp

    elif sortChoice == "2":
        temp = InsertionSort(array_to_be_sorted)
        temp.sortFully()
        return temp.sorted
        del temp

##      New sorting algorithms can be added
##      by simply adding a new option in sortChoice
##      and then adding a new elif statement here.

    else:
        raise ValueError("Invalid choice.")
コード例 #9
0
    def test_init(self):
        sortTest = SelectionSort(['a'])

        self.assertEqual(sortTest.unsorted, ['a'])
        self.assertEqual(sortTest.sorted, [])
コード例 #10
0
def main():
    check = Check()
    create = CreateRandomList()
    selectionSort = SelectionSort()
    bubbleSort = BubbleSort()
    insertionSort = InsertionSort()
    mergeSort = MergeSort()
    quickSort = QuickSort()
    heapSort = HeapSort()

    while True:
        system("cls")
        print(menu1)
        choice0 = input("Enter a number = ")
        if choice0 == "1":
            system("cls")

            small = int(input("Enter smallest number = "))
            big = int(input("Enter biggest number = "))
            length = int(input("Enter length = "))

            if check.checkLength(length) == True and check.checkSmallBig(small, big) == True:
                aList = create.createList(small, big, length)
                print(createdList.format(aList), end="\n\n")
                while True:
                    print(menu2)
                    choice1 = input("Enter a number = ")

                    if choice1 == "1":
                        tempList = aList.copy()
                        print(createdList.format(tempList), end="\n\n")
                        selectionSort.sort(tempList)
                        input(string1)
                    elif choice1 == "2":
                        tempList = aList.copy()
                        print(createdList.format(tempList), end="\n\n")
                        bubbleSort.sort(tempList)
                        input("PRESS ENTER or ANY INPUT")
                    elif choice1 == "3":
                        tempList = aList.copy()
                        print(createdList.format(tempList), end="\n\n")
                        insertionSort.sort(tempList)
                        input("PRESS ENTER or ANY INPUT")
                    elif choice1 == "4":
                        tempList = aList.copy()
                        print(createdList.format(tempList), end="\n\n")
                        mergeSort.sort(tempList)
                        input("PRESS ENTER or ANY INPUT")
                    elif choice1 == "5":
                        tempList = aList.copy()
                        print(createdList.format(tempList), end="\n\n")
                        quickSort.sort(tempList, 0, len(tempList)-1)
                        input("PRESS ENTER or ANY INPUT")
                    elif choice1 == "6":
                        tempList = aList.copy()
                        print(createdList.format(tempList), end="\n\n")
                        heapSort.sort(tempList)
                        input("PRESS ENTER or ANY INPUT")



            else:
                input("PRESS ENTER or ANY INPUT")
        elif choice0 == "0":
            quit()
コード例 #11
0
 def setUp(self):
     self.selectionSort = SelectionSort()
コード例 #12
0
class TestSelectionSort(unittest.TestCase):
    def setUp(self):
        self.selectionSort = SelectionSort()

    def test_0(self):
        print("{} Can create SelectionSort object".format(
            inspect.stack()[0][3]))

    def test_1(self):
        print(
            "{} When given list of unique positive numbers, can find lowest number"
            .format(inspect.stack()[0][3]))
        numberList = [3, 2, 5]
        self.assertEqual(
            numberList[self.selectionSort.findIndexOfLowestInList(numberList)],
            2)

    def test_2(self):
        print("{} When given list of unique numbers, can find lowest number".
              format(inspect.stack()[0][3]))
        numberList = [3, 2, -5]
        self.assertEqual(
            numberList[self.selectionSort.findIndexOfLowestInList(numberList)],
            -5)

    def test_3(self):
        print("{} When given list of numbers, can find lowest number".format(
            inspect.stack()[0][3]))
        numberList = [3, 2, 2, 5]
        self.assertEqual(
            numberList[self.selectionSort.findIndexOfLowestInList(numberList)],
            2)

    def test_4(self):
        print("{} Swapping numbers in small list, where from > to".format(
            inspect.stack()[0][3]))
        numberList = [2, 3, 4]
        self.assertEqual(self.selectionSort.swapFromTo(numberList, 2, 0),
                         [4, 3, 2])

    def test_5(self):
        print("{} Swapping numbers in small list, where from < to".format(
            inspect.stack()[0][3]))
        numberList = [2, 3, 4]
        self.assertEqual(self.selectionSort.swapFromTo(numberList, 0, 2),
                         [4, 3, 2])

    def test_6(self):
        print("{} Can sort small list".format(inspect.stack()[0][3]))
        numberList = [2, 3, 5, 6, 4, 7]
        self.assertEqual([2, 3, 4, 5, 6, 7],
                         self.selectionSort.sort(numberList))

    def test_7(self):
        print("{} Can sort HUGE list".format(inspect.stack()[0][3]))
        hugeList = self.generateHugeList(1000)
        sortedHugeList = self.selectionSort.sort(hugeList)
        for i, num in enumerate(sortedHugeList[:-1]):
            self.assertGreater(sortedHugeList[i + 1], sortedHugeList[i])

    def generateHugeList(self, length):
        return random.sample(range(length * 10), length)
コード例 #13
0
 algorithmUsed = args.method
 #获得需要排序的数据集
 fileName = args.data;            
 # 从文件读入数据,并使用读入的数据创建列表
 array=[]
 with open(fileName,'r') as f:
     for line in f:
         temp1 = line.strip('\n')
         temp2 = temp1.strip('\t')
         array.append(temp2)
         k = len(array)
     for i in range(len(array)):
         array.append(float(array[i]))
     del(array[0:k])
 # 选择合适的算法
 if algorithmUsed == 'bubble':
     sortAlgor = BubbleSort()
 elif algorithmUsed == 'select':
     sortAlgor = SelectionSort()
 else:
     print("Error: " + algorithmUsed + "is invalid.")
     array = None
     sys.exit(1)
 time_start=time.time()
 #排序
 array = sortAlgor.mysort(array)
 #length = len(array)
 #for num in range(length):
 #    print(array[num])
 time_end=time.time()
 print('Time cost:',time_end-time_start,'s')
コード例 #14
0
def main(algorithm, input_array):
	if algorithm == 'selection':
		selection_sort = SelectionSort(input_array)
		print(selection_sort.sort())
コード例 #15
0
	def setUp(self):
		self.selectionSort = SelectionSort()
コード例 #16
0
ファイル: Main.py プロジェクト: sscherbinas/Algorithms
from Bank import Bank
from QuickSort import QuickSort
from SelectionSort import SelectionSort

if __name__ == "__main__":
    banks_list = []
    name_pos = 0
    clients_pos = 1
    credits_pos = 2
    file = open('banks_list.csv')
    for line in file:
        values = line.split(',')
        bank = Bank(values[name_pos], int(values[clients_pos]),
                    int(values[credits_pos][:-1]))
        banks_list.append(bank)

    print("Selection sort:")
    selection_sort = SelectionSort(banks_list)
    start_time = time.clock()
    selection_sort.selection_sort()
    print("Time: " + str(time.clock() - start_time))
    for bank in banks_list:
        print(bank)

    print("\nQUICK sort:")
    quick_sort = QuickSort(banks_list)
    start_time = time.clock()
    quick_sort.quick_sort()
    print("Time: " + str(time.clock() - start_time))
    for bank in banks_list:
        print(bank)
コード例 #17
0
def BruteForceSelect(S, k):
    ''' len(S) is guarteen to be less than 5'''

    s = SelectionSort(S)
    return s[k - 1]
コード例 #18
0
    for book in books:
        print ""
        print "Book Number: " + str(index)
        print "Author: " + book.getAuthor().getLastName()
        print "Title: " + book.getTitle()
        print "Pages: " + book.getNumberPages()
        index += 1

# Extract book information from text files into array of Book objects
books100 = extractBooks("../googleBooks100.txt")
books1000 = extractBooks("../googleBooks1000.txt")
books10000 = extractBooks("../googleBooks10000.txt")

# Determine the duration to sort 100 books
startTime100 = timer()
SelectionSort.byAuthor(books100)
#SelectionSort.byNumberPages(books100)
#SelectionSort.byTitle(books100)
endTime100 = timer()
duration100 = (endTime100 - startTime100) * 1000 # Convert to milliseconds
print "Duration to sort 100 books: " + str(duration100)
printBooks(books100)

# Determine the duration to sort 1000 books
startTime1000 = timer()
SelectionSort.byAuthor(books1000)
#SelectionSort.byNumberPages(books1000)
#SelectionSort.byTitle(books1000)
endTime1000 = timer()
duration1000 = (endTime1000 - startTime1000) * 1000 # Convert to milliseconds
print "Duration to sort 1000 books: " + str(duration1000)
コード例 #19
0
print("\n----- INSERTION SORT -----\n")

numbers = Utils.get_numbers()
print("Unsorted numbers", numbers)
print("Sorted numbers", InsertionSort.sort(numbers))

characters = Utils.get_characters()
print("Unsorted characters", characters)
print("Sorted characters", InsertionSort.sort(characters))

# SELECTION SORT
print("\n----- SELECTION SORT -----\n")

numbers = Utils.get_numbers()
print("Unsorted numbers", numbers)
print("Sorted numbers", SelectionSort.sort(numbers))

characters = Utils.get_characters()
print("Unsorted characters", characters)
print("Sorted characters", SelectionSort.sort(characters))

strings = Utils.get_strings()
print("Unsorted string", strings)
print("Sorted strings", SelectionSort.sort(strings))

# BUBBLE SORT
print("\n----- BUBBLE SORT -----\n")

numbers = Utils.get_numbers()
print("Unsorted numbers", numbers)
print("Sorted numbers", BubbleSort.sort(numbers))