Search code examples
pythonalgorithmquicksort

i tryed to run a quick sort algorithm and this problem appears: unsupported operand type(s) for -: 'NoneType' and 'int'


guys! I don't understand what's wrong with this code for the Quick Sort Algorithm. Any help, please? I wrote it in Jupyter Notebook

    def quickSort (dados, inicio, fim):
        if inicio < fim:
            posicao_de_particionamento = partition (dados, inicio, fim)
            quickSort(dados, inicio, posicao_de_particionamento - 1)
            quickSort(dados, posicao_de_particionamento + 1, fim)
        
    def partition (dados, inicio, fim):
        pivo = dados[inicio]
        esq = inicio + 1
        dir = fim
        flag = False
        while not flag:
            while esq <= dir and dados[esq] <= pivo:
                esq = esq+1
            while dados[dir] >= pivo and dir >= esq:
                dir = dir-1
            if dir < esq:
                flag = True
            else:
                temp = dados[esq]
                dados[esq] = dados[dir]
                dados[dir] = temp
                return dir
            
            
            
            
    dados = [50, 51, 98, 85, 60, 66, 72, 33]
    quickSort (dados, 0, len(dados) - 1)
    print (dados)

what should I do?


Solution

  • Move return out of if:

        def partition (dados, inicio, fim):
            pivo = dados[inicio]
            esq = inicio + 1
            dir = fim
            flag = False
            while not flag:
                while esq <= dir and dados[esq] <= pivo:
                    esq = esq+1
                while dados[dir] >= pivo and dir >= esq:
                    dir = dir-1
                if dir < esq:
                    flag = True
                else:
                    temp = dados[esq]
                    dados[esq] = dados[dir]
                    dados[dir] = temp
            return dir