MC3305 Algoritmos e Estruturas de Dados II Aula 21 Ordenação externa Slides adaptados de Brian Cooper (Yahoo Research) Prof. Jesús P. Mena-Chalco jesus.mena@ufabc.edu.br 2Q-2015 1
Números de Ackermann 2
Problema: Ordenar um conjunto grande dados 3
1 acesso a disco Vários milhões de instruções de máquina Disk Access Time = Seek Time (moving disk head to correct track) + Rotational Delay (rotating disk to correct block in track) + Transfer Time (time to transfer block of data to main memory) 4
Por que ordenar? 5
Por que ordenar? Usuário geralmente quer os dados ordenados. Ordenar é o primeiro passo para carregar os dados em uma estrutura tipo árvore B+. Ordenar é muito útil para eliminar duplicações. (data deduplication) Criação de uma árvore geradora mínima. Projeção de objetos em um espaço 3D. 6
Algoritmos para ordenar elementos Baseado em comparações: Quicksort Mergesort Heapsort Selection sort Insertion sort Bubble sort Ordenação em tempo linear: Radix sort Ordenação de primeiros elementos (seleção parcial): Partial Quicksort 7
Algoritmos para ordenar elementos Baseado em comparações: Quicksort Mergesort Heapsort Selection sort Insertion sort Bubble sort Ordenação em tempo linear: Radix sort Ordenação de primeiros elementos (seleção parcial): Partial Quicksort Por que esses algoritmos não são úteis para bancos de dados? 8
Um problema de espaço RAM ROM 9
Um problema de espaço 4 GB: $300 480 GB: $300 Como ordenar dados cujo tamanho seja maior ao da memória principal? 10
Mergesort Banana Grapefruit Apple Orange Mango Kiwi Strawberry Blueberry Banana Grapefruit Apple Orange Mango Kiwi Strawberry Blueberry Banana Grapefruit Banana Grapefruit Apple Orange Apple Orange Mango Kiwi Kiwi Mango Strawberry Blueberry Blueberry Strawberry 11
Mergesort Banana Grapefruit Apple Orange Kiwi Mango Blueberry Strawberry Apple Banana Grapefruit Orange Apple Banana Blueberry Grapefruit Kiwi Mango Orange Strawberry Blueberry Kiwi Mango Strawberry 12
Não é bom o suficiente Considerando um arquivo com N registros. Para ordenar são necessários O(N logn) comparações. Queremos minimizar o acesso a disco (I/O) Não queremos pagar O(N logn) Ideia principal: Ordenação baseada em páginas, não em registros: Ler páginas completas na memória RAM (não registros individuais) Realizar alguma operação em memória principal. Escrever os bloco processados em memória secundária. Repetir. 13
2-way external merge sort etapas Pass 0: sort each page Sorted Unsorted RAM Pass 1: merge two pages into one run Sorted Sorted Sorted RAM Pass 2: merge two runs into one run Sorted Sorted Sorted Sorted! RAM 14
2-way external merge sort 15
2-way sort: custo computacional P pages in the file Each pass: read and wrote P pages How many passes? etapas Pass 0 Pass 1: went from P pages to P/2 runs Pass 2: went from P/2 runs to P/4 runs Total number of passes: Log2 P + 1 Total cost: 2P * ( Log2 P + 1) 16
2-way sort: custo computacional 17
2-way sort: custo computacional Why is this better than plain old merge sort? N >> P So O(N lg N) >> O(P lg P) Example: 1,000,000 record file 8 KB pages 100 byte records = 80 records per page = 12,500 pages Plain merge sort: 41,863,137 disk I/O s 2-way external merge sort: 365,241 disk I/O s 4.8 days versus 1 hour 18
Podemos fazer algo melhor? 2-way merge sort only uses 3 memory buffers Two buffers to hold input records One buffer to hold output records When that buffer fills up, flush to disk Usually we have a lot more memory than that Idea: read as much data into memory as possible each pass Thus reducing the number of passes Recall total cost: 2P * Passes 19
External merge sort Assign B input buffers and 1 output buffer Pass 0: Read in runs of B pages, sort, write to disk Pass 1: Merge B runs into one For each run, read one block When a block is used up, read next block of run Pass 2: Merge B runs into one Sorted! 20
External merge sort 21
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
Example Input Output
39
External merge sort P pages in file, B buffer pages in RAM P/B runs of size B Each pass: read and write P pages How many passes? LogB-1 P/B + 1 Total cost: 2P * LogB-1 P/B + 1 40
Exemplo 1,000,000 records in 12,500 pages Use 10 buffer pages in memory 4 passes 100,000 disk I/Os 17 minutes versus 1 hour for 2-way sort 41
Limitações Problem: CPU must wait for I/O Suppose I need to read a new block Stop merging Initiate I/O Wait Complete I/O Resume merging 42
Solution: double buffering Keep a second set of buffers Process one set while waiting for disk I/O to fill the other set Input Output
Solution: double buffering Keep a second set of buffers Process one set while waiting for disk I/O to fill the other set Input Output
Solution: double buffering Keep a second set of buffers Process one set while waiting for disk I/O to fill the other set Input Output
Solution: double buffering Keep a second set of buffers Process one set while waiting for disk I/O to fill the other set Input Output
Solution: double buffering Keep a second set of buffers Process one set while waiting for disk I/O to fill the other set Input Output
Solution: double buffering Keep a second set of buffers Process one set while waiting for disk I/O to fill the other set Input Output
Questões importantes Sorting is very important Basic algorithms not sufficient Assume memory access free, CPU is costly In databases, memory (e.g. disk) access is costly, CPU is (almost free) Try to minimize disk accesses 2-way sort: read and write records in blocks External merge sort: fill up as much memory as possible Double buffering: read and compute at the same time 49
Sobre as avaliações 50
51
Sobre a P2 Tópicos: Todos os tratados no quadrimestre (dia 13/08 estará disponível uma lista de exercício) Dia: 18/08 (com inicio -opcional- 30min antes do horário) Resumo: Pode trazer uma folha A4 contendo um resumo (feito a mao) 52