Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #define LIST_LENGTH 15
- #define RAND_SPREAD 10
- // struktura element listy
- class CElement
- {
- public:
- CElement* pNext;
- int nValue;
- // globalna glowa:
- static CElement* gpHead;
- };
- // inicjalizujemy glowe nullem bo nie istnieje jeszcze zaden element.
- CElement* CElement::gpHead = NULL;
- // lista dostępnych funkcji.
- void DisplayList(CElement*);
- void SelectionSort(CElement*);
- CElement* GetMinimum(CElement*);
- void SwapValues(CElement*, CElement*);
- // funkcja main
- int main( void )
- {
- // wiadomo.
- srand(time(NULL));
- // tworzymy 10 elementów listy i łączymy je w całość:
- CElement* pPrev = NULL;
- for (int i = 0; i < LIST_LENGTH; i++)
- {
- // new tworzy nowy obiekt struktury tak jak malloc.
- CElement* pElement = new CElement();
- // bezpieczna inicjalizacja.
- pElement->nValue = 0;
- pElement->pNext = NULL;
- pElement->nValue = rand() % RAND_SPREAD;
- printf("%d \n", pElement->nValue);
- // jak nie istnieje poprzedni to znaczy ze jestemy na samym poczatku (glowa)
- if (!pPrev)
- {
- CElement::gpHead = pElement;
- }
- else
- {
- pPrev->pNext = pElement;
- }
- // zapamietujemy poprzedni element zeby polaczyc go z kolejnym w nastepnej iteracji petli.
- pPrev = pElement;
- }
- // wyświetlamy zawartość listy po jej utworzeniu:
- printf("lista po utworzeniu: \n");
- DisplayList( CElement::gpHead );
- // sortujemy
- SelectionSort( CElement::gpHead );
- printf("lista po sortowaniu: \n");
- DisplayList( CElement::gpHead );
- return 0;
- }
- // wyświetla zawartość listy.
- void DisplayList( CElement* pElementZero )
- {
- CElement* pCurrent = pElementZero;
- while (pCurrent != NULL)
- {
- printf("%d ", pCurrent->nValue);
- pCurrent = pCurrent->pNext;
- }
- printf("\n");
- }
- // sortowanie przez proste wybieranie
- void SelectionSort( CElement* pElementZero )
- {
- CElement* pCurrent = pElementZero;
- CElement* pMinimum = NULL;
- // przejdz przez kolejne elementy listy.
- while (pCurrent != NULL)
- {
- // i kazdy kolejny swapnij z nowym minimum;
- pMinimum = GetMinimum( pCurrent );
- SwapValues(pCurrent, pMinimum);
- pCurrent = pCurrent->pNext;
- }
- }
- void SwapValues( CElement* operandA, CElement* operandB )
- {
- int temp;
- temp = operandA->nValue;
- operandA->nValue = operandB->nValue;
- operandB->nValue = temp;
- }
- // zwraca minimalna wartosc w liscie
- CElement* GetMinimum( CElement* pElementZero )
- {
- CElement* pCurrent = pElementZero;
- CElement* pMinimum = NULL;
- // sprawdz czy lista istnieje
- if (pCurrent)
- {
- pMinimum = pCurrent;
- }
- else
- {
- return NULL;
- }
- // a teraz porownujemy z kolejnymi
- while (pCurrent != NULL)
- {
- if (pMinimum->nValue >= pCurrent->nValue)
- {
- // nowe minimum.
- pMinimum = pCurrent;
- }
- pCurrent = pCurrent->pNext;
- }
- return pMinimum;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement