Explain the time and space complexity of a quicksort algorithm in both average and worst-case scenarios.