python3快速排序列表索引超出范围

时间:2017-11-12 00:34:56

标签: python debugging traceback

您好我是Python的新手,当我为快速排序算法实现以下代码时,我得到了一个回溯:“IndexError:列表索引超出范围”。

请有人帮助我。我整晚都在苦苦挣扎!

谢谢!

def quicksort(array,l,r):
    n = len(array)
    if n == 1 or n == 0:
        return array
    else:
        p = array[l]
        i = l + 1
        for j in range(l+1, r):
            if array[j] < p:
                array[i], array[j] = array[j], array[i]
                i = i + 1
        array[l], array[i-1] = array[i-1], array[l]
        array[l:i-1] = quicksort(array[l:i-1],l,i-1)
        array[i:r] = quicksort(array[i:r],i,r)
        return array

testarray = [1,3,4,5,2]
sortedarray = quicksort(testarray,0,5) 

1 个答案:

答案 0 :(得分:1)

修正了错误但你的排序逻辑错了,我想

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel;

namespace ProvEvents.Models
{
  [Table("User")]
  public class User
  {
    [Required]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity), Key()]
    public int UserID{ get; set; }

    [Required]
    [StringLength(50)]
    public string UserName{ get; set; }

    [Required]
    [DataType(DataType.Password)]
    [MinLength(8), MaxLength(12)]
    public string Password { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", 
    ApplyFormatInEditMode = true)]
    public DateTime RegisterDate { get; set; }

    [Required]
    [Phone]
    [RegularExpression(@"^([0-9]{10})$"]
    public string PhoneNumber{ get; set; }
   }
}

输出

def quicksort(array,l,r):
    n = len(array)
    if n == 1 or n == 0:
        return array
    else:
        p = array[l]
        i = l + 1
        for j in range(1, r-1):  # r is length of array; so range should be one less
            if array[j] < p:
                array[i], array[j] = array[j], array[i]
                i = i + 1
        array[l], array[i-1] = array[i-1], array[l]
        array[l:i-1] = quicksort(array[l:i-1],l,i-1)
        array[i:r] = quicksort(array[i:r],i,r)
        return array

testarray = [1,3,4,5,2]
sortedarray = quicksort(testarray,0,5) 

print(sortedarray)